user824624
user824624

Reputation: 8080

wrong to calculate the gaussian distribution in python

I am quite new to python, right now I am using python to do a exercise on computing the Gaussian distribution.

Here in the example, mean is 100, standard deviation is 10, then I need to calculate the pdf in 90 and 110.

my code is like

def gaussian_distribution(x , mean, dev):
    k = 1.0/ (dev * math.sqrt(2*math.pi))
    s = -1.0/ ( 2* dev*dev )
    return k * math.exp( (x-mean)*(x-mean) * s )

print gaussian_distribution( 110, 100, 10), gaussian_distribution( 90, 100, 10)

but the values are both 0.0241970724519, which is wrong, different from the answer 0.84 and 0.1 from online calculator.

I don't know what goes wrong with my function in python

Upvotes: 1

Views: 123

Answers (1)

ev-br
ev-br

Reputation: 26110

Your pdf is correct, while your online calculator gives you cdf, the cumulative distribution function.

The latter is, by definition, an integral of the pdf from negative infinity to the argument, so:

>>> from scipy.integrate import quad
>>> quad(gaussian_distribution, -np.inf, 110, args=(100., 10.))
(0.841344746068544, 1.1360408153147754e-08)

Unless it's a self-inflicted learning exercise, just use scipy.stats:

>>> from scipy.stats import norm
>>> norm.pdf(110, loc=100., scale=10.)
0.024197072451914336
>>> norm.cdf(110, loc=100., scale=10.)
0.84134474606854293

Upvotes: 2

Related Questions