Generate random numbers with fixed total python result

Asked

Viewed 246 times

1

I need to generate three random numbers and the sum of those has to be 1.0. follows the idea more or less, I believe that the way I’m doing would take too long to reach a..

import random

total = 1.0
x1= 0.0
x2= 0.0
x3= 0.0
while(x1+x2+x3)!=total:
  x1= random.uniform(0.1, 0.45)
  x2= random.uniform(0.1, 0.45)
  x3= random.uniform(0.1, 0.45)

print(x1, x2,x3)
  • Why not just generate two random numbers and make the third being x3 = total-x1-x2? Thus ensures that the sum will always be total and that the three values are random.

  • I will abide by your idea :)

1 answer

2

As suggested by Anderson in the comments, you calculate just

x3 = total - x1 - x2

However, note that when changing the calculation of x3 and maintain the calculations of x1 and x2 as it stands, the average value of x3 would be of E[x3] = E[total] - E[x1] - E[x2] = 1 - 0.55 = 0.45[1], and thus, the variables defined would have random values, but their probabilistic distributions would be different.

In practice, this means that larger values will usually be drawn for x3 than for other variables.


If this behavior is inconvenient, you can calculate the three variables with

  x1= random.uniform(0.1, 0.45)
  x2= random.uniform(0.1, 0.45)
  x3= random.uniform(0.1, 0.45)

then calculate its sum

  somatório = x1 + x2 + x3

to finally get variables

x1Modificado = x1/somatório

x2Modificado = x2/somatório

x3Modificado = x3/somatório

and thus the sum of x1Modificado, x2Modificado and x3Modificado will be 1.


[1] Value obtained using the formula of the mean of uniform distribution: (1/2)*(b+a).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.