2

In a Python program, I need to generate normally-distributed random numbers with a specific, user-controlled variance. How can I do this?

thornate
  • 4,902
  • 9
  • 39
  • 43

3 Answers3

11

Use random.normalvariate (or random.gauss if you don't need thread-safety), and set the sigma argument to the square root of the variance.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
7
import math
from random import gauss

my_mean = 0
my_variance = 10

random_numbers = [gauss(my_mean, math.sqrt(my_variance)) for i in range(100)]

This gets you 100 normally-distributed random numbers with mean 0 and variance 10.

David Robinson
  • 77,383
  • 16
  • 167
  • 187
1

If you want to sample from a specific range of numbers, you can do it like this:

mu = 350
variance = 10
sigma = math.sqrt(variance)
x = np.linspace(1,572,572)
p = scipy.stats.norm.pdf(x, mu, sigma)
random_number = np.random.choice(x, p=p/np.sum(p))

This way, we can also plot the distribution:

plt.plot(x, p)
plt.show()

enter image description here

Amir P
  • 123
  • 5