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

Viewed 195

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?

2 Answers

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

I found a better solution for this problem. The below code gives you random |N| values from the uniform distribution over ( 0 , 1 ), normalizing the sum to equal 1.
Note that you necessarily need to use the uniform method so that you can normalize the sum exactly equal 1.

import numpy as np
import random
Sum = 0

probs = np.random.uniform(size = 5)
normalizer = 1/probs.sum()
probs = probs * normalizer

for p in probs:
 Sum += p

difference = 1-Sum
rand_value = random.choice(range(len(probs)))
probs[rand_value] += difference
 
print(probs, probs.sum())
Related