Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy, how to generate a normally distributed set of integers

What is the best way to generate a normally distributed set of integers with numpy? I know I can get floats with something like this:

In [31]: import numpy as np

In [32]: import matplotlib.pyplot as plt

In [33]: plt.hist(np.random.normal(250, 1, 100))
Out[33]: 
(array([  2.,   5.,   9.,  10.,  19.,  21.,  13.,  10.,   6.,   5.]),
 array([ 247.52972483,  247.9913017 ,  248.45287858,  248.91445546,
         249.37603233,  249.83760921,  250.29918608,  250.76076296,
         251.22233984,  251.68391671,  252.14549359]),
 <a list of 10 Patch objects>)

histogram

like image 895
tbc Avatar asked Oct 15 '15 23:10

tbc


1 Answers

The Binomial Distribution is a good discrete approximation of the Normal distribution. Namely,

Binomial(n, p) ~ Normal(n*p, sqrt(n*p*(1-p)))

So you could do

import numpy as np
import matplotlib.pyplot as plt
from math import sqrt

bi = np.random.binomial(n=100, p=0.5, size=10000)
n = np.random.normal(100*0.5, sqrt(100*0.5*0.5), size=10000)

plt.hist(bi, bins=20, normed=True);
plt.hist(n, alpha=0.5, bins=20, normed=True);
plt.show();

enter image description here

like image 169
o-90 Avatar answered Oct 21 '22 17:10

o-90