Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating N numbers that sum to 1

Given an array of size n I want to generate random probabilities for each index such that Sigma(a[0]..a[n-1])=1

One possible result might be:

0     1     2     3     4
0.15  0.2   0.18  0.22  0.25

Another perfectly legal result can be:

0     1     2     3     4
0.01  0.01  0.96  0.01  0.01

How can I generate these easily and quickly? Answers in any language are fine, Java preferred.

like image 533
Yuval Adam Avatar asked Jan 31 '10 08:01

Yuval Adam


People also ask

What three numbers add up to 1?

(1, 0, 0), an equally valid triple, must come from (1, 0, 0). One solution: The set of positive numbers that add to 1 form a n equilateral triangle in three-space, with coordinates (1,0,0), (0,1,0), (0,0,1).

How do you generate a sum of random numbers?

You could use the RAND() function to generate N numbers (8 in your case) in column A. Then, in column B you could use the following formula B1=A1/SUM(A:A)*320 , B2=A2/SUM(A:A)*320 and so on (where 320 is the sum that you are interested into). So you can just enter =RAND() in A1, then drag it down to A8.

How do you sum a random list in Python?

Method #2 : Using random.sample() + sum() This single utility function performs the exact required as asked by the problem statement, it generated N no. of random numbers in a list in the specified range and returns the required list. The task of performing sum is done using sum().

How do you generate random 50 numbers in Python?

The randint() method to generates a whole number (integer). You can use randint(0,50) to generate a random number between 0 and 50. To generate random integers between 0 and 9, you can use the function randrange(min,max) .


1 Answers

Get n random numbers, calculate their sum and normalize the sum to 1 by dividing each number with the sum.

like image 71
Kobi Avatar answered Oct 02 '22 07:10

Kobi