Skip to content Skip to sidebar Skip to footer

Random Number With Specific Variance In Python

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

Solution 1:

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.

Solution 2:

import math
from random importgaussmy_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.

Solution 3:

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

mu = 350variance = 10sigma = 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

Post a Comment for "Random Number With Specific Variance In Python"