Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random normal distribution of integers

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.

like image 886
Ghilas BELHADJ Avatar asked May 24 '16 10:05

Ghilas BELHADJ


People also ask

How do you find the normal distribution of a number?

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.


1 Answers

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:

enter image description here

like image 78
ayhan Avatar answered Oct 02 '22 16:10

ayhan