How to generate a random integer as with np.random.randint()
, but with a normal distribution around 0.
np.random.randint(-10, 10)
returns integers with a discrete uniform distribution np.random.normal(0, 0.1, 1)
returns floats with a normal distribution
What I want is a kind of combination between the two functions.
To standardize a value from a normal distribution, convert the individual value into a z-score: Subtract the mean from your individual value. Divide the difference by the standard deviation.
One other way to get a discrete distribution that looks like the normal distribution is to draw from a multinomial distribution where the probabilities are calculated from a normal distribution.
import scipy.stats as ss import numpy as np import matplotlib.pyplot as plt x = np.arange(-10, 11) xU, xL = x + 0.5, x - 0.5 prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3) prob = prob / prob.sum() # normalize the probabilities so their sum is 1 nums = np.random.choice(x, size = 10000, p = prob) plt.hist(nums, bins = len(x))
Here, np.random.choice
picks an integer from [-10, 10]. The probability for selecting an element, say 0, is calculated by p(-0.5 < x < 0.5) where x is a normal random variable with mean zero and standard deviation 3. I chose a std. dev. of 3 because this way p(-10 < x < 10) is almost 1.
The result looks like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With