How to generate random normal distribution of integers

How to generate a random integer 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

I want this to be a combination between two functions.

+6
source share
2 answers

Another possible way to obtain a discrete distribution similar to the normal distribution is to extract from the multinomial distribution, where the probabilities are calculated from the 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 selects an integer from [-10, 10]. The probability of choosing an element, say 0, is calculated using p (-0.5 <x <0.5) where x is a normal random variable with an average zero and a standard deviation of 3. I am chooce std. deviation as 3, because in this way p (-10 <x <10) is almost 1.

The result is as follows:

enter image description here

+16
source

It is possible to create a similar distribution from Truncated Normal Distribution , rounded to the nearest integer. Here is an example with scipy truncnorm () .

 import numpy as np from scipy.stats import truncnorm import matplotlib.pyplot as plt scale = 3. range = 10 size = 100000 X = truncnorm(a=-range/scale, b=+range/scale, scale=scale).rvs(size=size) X = X.round().astype(int) 

Let's see how it looks.

 bins = 2 * range + 1 plt.hist(X, bins) 

enter image description here

+5
source

All Articles