473,748 Members | 11,145 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 #1
14 9894
Anthony Liu wrote:
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.
numbers.append (random.uniform (0, 1.0-sum(numbers)))

might help, perhaps.

or

scaled = [x/sum(numbers) for x in numbers]

Mel.

Apr 22 '06 #2
Anthony Liu wrote:
But, I want the random numbers just generated sum up
to 1 .


This seems like an odd request. Might I ask what it's for?

Generating random numbers in [0,1) that are both uniform and sum to 1 looks
like an unsatisfiable task. Each number you generate restricts the
possibilities for future numbers. E.g. if the first number is 0.5, all
future numbers must be < 0.5 (indeed, must *sum* to 0.5). You'll end up
with a distribution increasingly skewed towards smaller numbers the more
you generate. I can't imagine what that would be useful for.

If that's not a problem, do this: generate the numbers, add them up, and
divide each by the sum.

nums = [random.uniform( 0,1) for x in range(0,100)]
sum = reduce(lambda x,y: x+y, nums)
norm = [x/sum for x in nums]

Of course now the numbers aren't uniform over [0,1) anymore.

Also note that the sum of the normalized numbers will be very close to 1,
but slightly off due to representation issues. If that level of accuracy
matters, you might consider generating your rands as integers and then
fp-dividing by the sum (or just store them as integers/fractions).
Apr 22 '06 #3
Em Sáb, 2006-04-22 Ã*s 03:16 +0000, Edward Elliott escreveu:
If that level of accuracy
matters, you might consider generating your rands as integers and then
fp-dividing by the sum (or just store them as integers/fractions).


Or using decimal module: http://docs.python.org/lib/module-decimal.html

--
Felipe.

Apr 22 '06 #4
Anthony Liu <an***********@ yahoo.com> wrote:
...
As a matter of fact, given that we have to specify the
number of states for an HMM, I would like to create a
specified number of random floating numbers whose sum
is 1.0.


def forAL(N):
N_randoms = [random.random() for x in xrange(N)]
total = sum(N_randoms)
return [x/total for x in N_randoms]
Does this do what you want? Of course, the resulting numbers are not
independent, but then the constraints you pose would contradict that.
Alex
Apr 22 '06 #5

Anthony Liu wrote:
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.


--------------------------------------------------------------
import random

def partition(start =0,stop=1,eps=5 ):
d = stop - start
vals = [ start + d * random.random() for _ in range(2*eps) ]
vals = [start] + vals + [stop]
vals.sort()
return vals

P = partition()

intervals = [ P[i:i+2] for i in range(len(P)-1) ]

deltas = [ x[1] - x[0] for x in intervals ]

print deltas

print sum(deltas)
---------------------------------------------------------------

Gerard

Apr 22 '06 #6

Gerard Flanagan wrote:
Anthony Liu wrote:
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.


--------------------------------------------------------------
import random

def partition(start =0,stop=1,eps=5 ):
d = stop - start
vals = [ start + d * random.random() for _ in range(2*eps) ]
vals = [start] + vals + [stop]
vals.sort()
return vals

P = partition()

intervals = [ P[i:i+2] for i in range(len(P)-1) ]

deltas = [ x[1] - x[0] for x in intervals ]

print deltas

print sum(deltas)
---------------------------------------------------------------


def partition(N=5):
vals = sorted( random.random() for _ in range(2*N) )
vals = [0] + vals + [1]
for j in range(2*N+1):
yield vals[j:j+2]

deltas = [ x[1]-x[0] for x in partition() ]

print deltas

print sum(deltas)

[0.1027196668699 4982, 0.1382657649104 2208, 0.0641469135551 32801,
0.1190645245446 7387, 0.1050119845609 1299, 0.0117324238307 68779,
0.1178536925644 2912, 0.0659271655201 02249, 0.0983513058781 76198,
0.0777867470762 05365, 0.0991398106892 26726]
1.0

Apr 22 '06 #7
Gerard Flanagan wrote:
Gerard Flanagan wrote:
Anthony Liu wrote:
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.


--------------------------------------------------------------
import random

def partition(start =0,stop=1,eps=5 ):
d = stop - start
vals = [ start + d * random.random() for _ in range(2*eps) ]
vals = [start] + vals + [stop]
vals.sort()
return vals

P = partition()

intervals = [ P[i:i+2] for i in range(len(P)-1) ]

deltas = [ x[1] - x[0] for x in intervals ]

print deltas

print sum(deltas)
---------------------------------------------------------------


def partition(N=5):
vals = sorted( random.random() for _ in range(2*N) )
vals = [0] + vals + [1]
for j in range(2*N+1):
yield vals[j:j+2]

deltas = [ x[1]-x[0] for x in partition() ]

print deltas

print sum(deltas)


finally:

---------------------------------------------------------------
def distribution(N= 2):
p = [0] + sorted( random.random() for _ in range(N-1) ) + [1]
for j in range(N):
yield p[j+1] - p[j]

spread = list(distributi on(10))

print spread
print sum(spread)
---------------------------------------------------------------
Gerard

Apr 22 '06 #8
Gerard Flanagan <gr********@yah oo.co.uk> wrote:
def distribution(N= 2):
p = [0] + sorted( random.random() for _ in range(N-1) ) + [1]
for j in range(N):
yield p[j+1] - p[j]

spread = list(distributi on(10))

print spread
print sum(spread)


This is simpler, easier to prove correct and most likely quicker.

def distribution(N= 2):
L = [ random.uniform( 0,1) for _ in xrange(N) ]
sumL = sum(L)
return [ l/sumL for l in L ]

spread = distribution(10 )
print spread
print sum(spread)

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Apr 23 '06 #9
Nick Craig-Wood wrote:
Gerard Flanagan <gr********@yah oo.co.uk> wrote:
def distribution(N= 2):
p = [0] + sorted( random.random() for _ in range(N-1) ) + [1]
for j in range(N):
yield p[j+1] - p[j]

spread = list(distributi on(10))

print spread
print sum(spread)


This is simpler, easier to prove correct and most likely quicker.

def distribution(N= 2):
L = [ random.uniform( 0,1) for _ in xrange(N) ]
sumL = sum(L)
return [ l/sumL for l in L ]


simpler:- ok

easier to prove correct:- in what sense?

quicker:- slightly slower in fact (using xrange in both functions).
This must be due to 'uniform' - using random() rather than uniform(0,1)
then yes, it's quicker. Roughly tested, I get yours (and Alex
Martelli's) to be about twice as fast. (2<=N<1000, probably greater
difference as N increases).

All the best.

Gerard

Apr 23 '06 #10

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

Similar topics

1
30925
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
3630
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
24540
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
5228
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
9955
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
2775
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
25473
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
6606
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
7225
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
8989
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
9537
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9319
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
8241
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...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2213
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.