Alternative for scipy.stats.norm.pdf?

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

Does anyone know of an alternative for scipy.stats.norm.pdf()? I'm hosting my python site on Google App Engine and Google doesn't support SciPy.

I've tried this function, but that didn't return the same results as scipy:

def normpdf(x, mu, sigma):     u = (x-mu)/abs(sigma)     y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2)     return y 

For example:

print scipy.stats.norm.pdf(20, 20, 10) print normpdf(20, 20, 10)  print scipy.stats.norm.pdf(15, 20, 10) print normpdf(15, 20, 10)  print scipy.stats.norm.pdf(10, 20, 10) print normpdf(10, 20, 10) 

Returns these values:

0.0398942280401 0.0398942280401  0.0352065326764 0.0146762663174  0.0241970724519 0.0146762663174 

回答1:

You got tricked by pythons integer division arithmetics! Here is some working code:

from __future__ import division  import scipy.stats from numpy import *  def normpdf(x, mu, sigma):     u = (x-mu)/abs(sigma)     y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2)     return y   print scipy.stats.norm.pdf(20, 20, 10) print normpdf(20, 20, 10)  print scipy.stats.norm.pdf(15, 20, 10) print normpdf(15, 20, 10)  print scipy.stats.norm.pdf(10, 20, 10) print normpdf(10, 20, 10) 

Note the first line! Otherwise, you could convert each input variable to a float, e.g. by multiplying by 1.



回答2:

The division by 2 inside of the exp is being interpreted as integer division whenever u evaluates to an int. To prevent this you can ensure that u always evaluates to a float by manually casting it:

def normpdf(x, mu=0, sigma=1):     u = float((x-mu) / abs(sigma))     y = exp(-u*u/2) / (sqrt(2*pi) * abs(sigma))     return y 

(I also provided default arguments for mu and sigma, you could remove those if you wanted)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!