mardi 26 septembre 2023

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.




Aucun commentaire:

Enregistrer un commentaire