473,763 Members | 9,275 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generate a sequence of random numbers that sum up to 1?

I am at my wit's end.

I want to generate a certain number of random numbers.
This is easy, I can repeatedly do uniform(0, 1) for
example.

But, I want the random numbers just generated sum up
to 1 .

I am not sure how to do this. Any idea? Thanks.

_______________ _______________ _______________ _____
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
Apr 22 '06
14 9903
I'm surprised noone has pursued a course of subtraction rather than
division. Say you want 10 numbers:
s = 1.0
n = []
for x in xrange(9): .... value = random.random() * s
.... n.append(value)
.... s -= value
.... n.append(s)
n [0.7279111122901 516, 0.0821287086068 67745, 0.0080516733577 621798,
0.1212206024590 2817, 0.0034460458833 209676, 0.0021046234724 371184,
0.0541094249143 63845, 0.0003575097024 9204185, 0.0005117507553 6832372,
0.0001585485582 0800087] sum(n)

1.0
Either:
1) Just because they're *ordered* doesn't mean they're not *random*,
or
2) You all now know why I'm not a mathematician. ;)

It seems to me that the only constraint on the randomness of my results
is the OP's constraint: that they sum to 1. I'd be fascinated to learn
if and why that wouldn't work.
Robert Brewer
System Architect
Amor Ministries
fu******@amor.o rg

Apr 23 '06 #11
fumanchu <fu******@amor. org> wrote:
I'm surprised noone has pursued a course of subtraction rather than
division. Say you want 10 numbers:
s = 1.0
n = []
for x in xrange(9): ... value = random.random() * s
... n.append(value)
... s -= value
... n.append(s)
n [0.7279111122901 516, 0.0821287086068 67745, 0.0080516733577 621798,
0.1212206024590 2817, 0.0034460458833 209676, 0.0021046234724 371184,
0.0541094249143 63845, 0.0003575097024 9204185, 0.0005117507553 6832372,
0.0001585485582 0800087] sum(n)

1.0
Either:
1) Just because they're *ordered* doesn't mean they're not *random*,
or
2) You all now know why I'm not a mathematician. ;)

It seems to me that the only constraint on the randomness of my results
is the OP's constraint: that they sum to 1. I'd be fascinated to learn
if and why that wouldn't work.


n[0] is uniformly distributed between 0 and 1; n[1] is not -- not sure
how to characterize its distribution, but it's vastly skewed to favor
smaller values -- and further n[x] values for x>1 are progressively more
and more skewed similarly.

Such total disuniformity, where the very distribution of each value is
skewed by the preceding one, may still be "random" for some sufficiently
vague meaning of "random", but my intuition suggests it's unlikely to
prove satisfactory for the OP's purposes.
Alex
Apr 23 '06 #12
Alex Martelli wrote:
fumanchu <fu******@amor. org> wrote:
I'm surprised noone has pursued a course of subtraction rather than
division. Say you want 10 numbers:
>s = 1.0
>n = []
>for x in xrange(9):


... value = random.random() * s
... n.append(value)
... s -= value
...
>n.append(s )
>n


[0.7279111122901 516, 0.0821287086068 67745, 0.0080516733577 621798,
0.12122060245 902817, 0.0034460458833 209676, 0.0021046234724 371184,
0.05410942491 4363845, 0.0003575097024 9204185, 0.0005117507553 6832372,
0.00015854855 820800087]
>sum(n)


1.0

Either:
1) Just because they're *ordered* doesn't mean they're not *random*,
or
2) You all now know why I'm not a mathematician. ;)

It seems to me that the only constraint on the randomness of my results
is the OP's constraint: that they sum to 1. I'd be fascinated to learn
if and why that wouldn't work.


n[0] is uniformly distributed between 0 and 1; n[1] is not -- not sure
how to characterize its distribution, but it's vastly skewed to favor
smaller values -- and further n[x] values for x>1 are progressively more
and more skewed similarly.

Such total disuniformity, where the very distribution of each value is
skewed by the preceding one, may still be "random" for some sufficiently
vague meaning of "random", but my intuition suggests it's unlikely to
prove satisfactory for the OP's purposes.


[digression]

All of this discussion about whether the distribution of values is uniform or
not doesn't mean much until one has defined "uniformity ," or equivalently,
"distance" in the space we're talking about. In this case, we're talking about
the unit n-simplex space (SS^n) which has elements S=(s_1, s_2, ... s_n) where
sum(S) = 1 and s_i >= 0. I favor the Aitchison distance:

import numpy as np

def aitchison_dista nce(x, y):
""" Compute the Aitchison distance between two vectors in simplex space.
"""
lx = np.log(x)
ly = np.log(y)
lgx = np.mean(lx, axis=-1)
lgy = np.mean(ly, axis=-1)
diff = (lx - lgx) - (ly - lgy)
return np.sqrt(np.sum( diff*diff))

Note that zeros yield inifinities, so the borders of the unit simplex are
infinitely farther away from other points in the interior. Consequently,
generating "uniform" random samples from this space is as impractical as it is
to draw "uniform" random samples from the entire infinite real number line. It's
also not very interesting. However, one can transform SS^n into RR^(n-1) and
back again, so drawing numbers from a multivariate normal of whatever mean and
covariance you like will give you "nice" simplicial data and quite possibly even
realistic data, too, depending on your model. I like using the isometric
log-ratio transform ("ilr" transform) for this.

Good Google search terms: "compositio nal data", Aitchison

But of course, for the OP's purpose of creating synthetic Markov chain
transition tables, generating some random vectors uniformly on [0, 1)^n and
normalizing them to sum to 1 works a treat. Don't bother with anything else.

--
Robert Kern
ro*********@gma il.com

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Apr 23 '06 #13
Alex Martelli wrote:
Such total disuniformity, where the very distribution of each value is
skewed by the preceding one, may still be "random" for some sufficiently
vague meaning of "random", but my intuition suggests it's unlikely to
prove satisfactory for the OP's purposes.


It does seem very odd. If you could restrict the range, you could get an
unskewed distribution. Set range = (0, 2*sum/cnt) and you can generate cnt
numbers whose sum will tend towards sum (because the average value will be
sum/cnt):

target_sum = 1
cnt = 100
max = 2.0 * target_sum / cnt # 0.02
nums = [random.uniform( 0,max) for x in range(0,cnt)]
real_sum = sum(nums) # 0.975... in one sample run

If the sum has to be exact, you can set the last value to reach it:

nums[-1] = target_sum - sum(nums[:-1])
print sum(nums) # 1.0

which skews the sample ever so slightly. And check for negatives in case
the sum exceeded the target.

If the exact count doesn't matter, just generate random nums until you're
within some delta of the target sum.

Basically, there usually better options to the problem as originally posed.
Actually, now that I reread it the OP never said the range had be [0,1).
So maybe we read too much into the original phrasing. If you need
anything resembling a uniform distribution, scaling the results afterward
is not the way to go.
Apr 23 '06 #14

"fumanchu" <fu******@amor. org> wrote in message
news:11******** **************@ j33g2000cwa.goo glegroups.com.. .
I'm surprised noone has pursued a course of subtraction rather than
division.


I believe someone did mention the subtraction method in one of the initial
responses. But the problem is this. If you independently sample n numbers
from a given distribution and then rescale, then the scaled numbers still
all have the same distribution (and are uniform in that sense). In the
subtraction method, each comes from a differnt distribution, as others
explained, with the nth being radically different from the first.

Terry Jan Reedy

Apr 24 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
30928
by: Intaek LIM | last post by:
generally, we use srand(time(0)) to generate random numbers. i know why we use time(0), but i can not explain how it operates. first, see example source below. --------------------------------------------- #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv)
10
3633
by: Johannes Veerkamp | last post by:
hi there, i'm a newbie in c and i'd like to write a programm which generates random numbers from 1 to 10 (integers). can anybody help me out with the correct code? thanx
5
2399
by: cvnweb | last post by:
I am trying to generate 2 random numbers that are diffrent, in order to add them to existing numbers to generate numbers that start out the same, but are randomly added and subtracted so that they can go down similar paths, but not be the same. I will implement code later to make sure i they go more than 10 apart from each other that they are moved closer together, but this is what I have so far, and when the program is run, the two random...
3
24548
by: JoelPJustice | last post by:
I am working through a VBA book by myself to help and try and improve my skills. However, the book does not give you solutions to certain problems. I have worked through this problem up until bullet point 3. Here is the code I came up with up until now. Function RandomNormal(Mean As Double, StdDev As Double) As Double Application.Volatile Randomize RandomNormal = (StdDev * Sqr(-2 * Log(Rnd)) * Cos(2 * 3.141596 * Rnd)) + Mean End...
12
5229
by: Jim Michaels | last post by:
I need to generate 2 random numbers in rapid sequence from either PHP or mysql. I have not been able to do either. I get the same number back several times from PHP's mt_rand() and from mysql's RAND(). any ideas? I suppose I could use the current rancom number as the seed for the next random number. but would that really work?
9
9956
by: MyInfoStation | last post by:
Hi all, I am a newbie to Python and would like to genereate some numbers according to geometric distribution. However, the Python Random package seems do not have implemented functionality. I am wondering is there exist any other libraries that can do this job? Thanks a lot, Da
6
2779
by: Anamika | last post by:
I am doing a project where I want to generate random numbers for say n people.... These numbers should be unique for n people. Two people should not have same numbers.... Also the numbers should not be repeted.. Do anyone have some nice algorithm for that? Or anyone can suggest me any type of book or site for that purpose?
8
25477
by: kiranchahar | last post by:
Hey all, How do I generate random numbers with Uniform distribution Uniform(a,b) using C-programming? I want to generate uniform random numbers which have mean following Uniform(p,q) and also variance as Uniform(s,t)? any suggestion would be really appreciated. Thanks, Kay
9
6608
by: Chelong | last post by:
Hi All I am using the srand function generate random numbers.Here is the problem. for example: #include<iostream> #include <time.h> int main() {
24
7232
by: pereges | last post by:
I need to generate two uniform random numbers between 0 and 1 in C ? How to do it ? I looked into rand function where you need to #define RAND_MAX as 1 but will this rand function give me uniformly distributed and unique numbers ?
0
9564
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9387
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9938
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.