Search code examples
pythonmathrandomprobability

How to generate uniform random numbers in Python close to the true mean and standard deviation?


I am trying to generate uniform random numbers as much as possible close to its theoretical definition, particularly in Python. (i.e., I am familiar with the concept of Pesudo-Random Generators (PRGs) in programming languages.)

I am using the following code for this matter (a widely known solution):

import random
import numpy as np

rands = []
rng = random.Random(5)

for i in range(10000):
  rands.append(rng.uniform(0,1))


print(f"mean: {np.mean(rands)}")
print(f"std: {np.std(rands)}")

The result is:

mean: 0.501672056714862
std: 0.2880418652775188

By changing the initial seed, we can observe that we will get approximately the same values.

On the other hand, from the theoretical aspect, we know that the mean and standard deviation (std) of a uniform random variable between [0, 1] are equal to 0.5 and 1/12 (~ 0.08333), respectively.

As we can observe, the std of generated random numbers is more than 1/4 (3 times more than the theoretical one).

Hence, a plausible question is "how should I adjust this implementation to get a closer std to the theoretical one?"

I understand that the rationale behind this difference originated in the core implementation of the PRG used in the random function. But, I am looking for any other method to resolve this issue.

Update:

It is just a confusion between variance and std, as answered in the following!


Solution

  • I think you're confusing standard deviation and variance.
    For a uniform distribution the mean is (a+b) / 2 and the variance ( which is std^2 ) is (b-a)^2/12.
    So the standard deviation becomes the square root of (b-a)^2/12 which is simply (b-a)/sqrt(12)

    >>> 1/sqrt(12)
    0.2886751345948129
    

    Pretty close to your standard deviation.

    source