Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

math - Generating Random |N| Values from the Uniform Distribution over ( 0 , 1 ) and Normalizing the Sum to Equal 1 in Python

This may be a repetitive topic but I have a different problem on this topic and the existing answers didn't help me.
I want to generate some random values from the uniform distribution over (0,1) in my python application and normalizing the sum to equal one.
The problem is that the sum of generated values is not exactly equal to one. On each group of normalized random values, the sum for example equals to 0.99999999999 or 1.00000000056. I have tried some tricks but couldn't solve the issue. This is what I have done so far:

sum = 0
probs = []
for i in range(10):
    probs += [random.uniform(0, 1)]

prob = np.array(probs)

for p in prob:
 p /= prob.sum()  # normalize
 sum += p

print(sum)

Does anyone know how to generate these numbers so that their sum equals exactly 1?

question from:https://stackoverflow.com/questions/66058874/generating-random-n-values-from-the-uniform-distribution-over-0-1-and-no

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The sum is not exactly equal to 1.0, because of floating point errors, not related to numpy or python. But, you can modify last element to account for that error. Like:

probs = np.random.random(10)
probs = probs / probs.sum()
probs[-1] = 1 - probs[:-1].sum()
probs.sum()
>>>
1.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...