我正在寻找在Numpy或Scipy(或任何严谨的Python库)中提供正态分布累积函数的函数。
这是一个例子:
>>> from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435
换句话说,标准正态区间的约95%位于以标准均值零为中心,两个标准偏差内。
如果需要反函数累积分布:
>>> norm.ppf(norm.cdf(1.96))
array(1.9599999999999991)
也许回答这个问题已经太晚了,但既然Google仍然将人们带到这里,我决定在这里写下我的解决方案。
也就是说,自Python 2.7以来,math
库已经集成了误差函数math.erf(x)
erf()
函数可用于计算传统的统计函数,例如累积标准正态分布:
from math import *
def phi(x):
#'Cumulative distribution function for the standard normal distribution'
return (1.0 + erf(x / sqrt(2.0))) / 2.0
参考文献:
https://docs.python.org/2/library/math.html
def phi(x, mu, sigma): return (1 + erf((x - mu) / sigma / sqrt(2))) / 2
。其中,mu为均值,sigma为标准差,erf为误差函数,sqrt为平方根函数。 - Bernhard Barker从Python 3.8开始,标准库提供了NormalDist
对象作为statistics
模块的一部分。
它可用于获取给定均值(mu
)和标准偏差(sigma
)的累积分布函数(cdf
- 随机样本X小于或等于x的概率):
from statistics import NormalDist
NormalDist(mu=0, sigma=1).cdf(1.96)
# 0.9750021048517796
对于标准正态分布(mu = 0
,sigma = 1
),可以简化为:
NormalDist().cdf(1.96)
# 0.9750021048517796
NormalDist().cdf(-1.96)
# 0.024997895148220428
源自这里 http://mail.python.org/pipermail/python-list/2000-June/039873.html
from math import *
def erfcc(x):
"""Complementary error function."""
z = abs(x)
t = 1. / (1. + 0.5*z)
r = t * exp(-z*z-1.26551223+t*(1.00002368+t*(.37409196+
t*(.09678418+t*(-.18628806+t*(.27886807+
t*(-1.13520398+t*(1.48851587+t*(-.82215223+
t*.17087277)))))))))
if (x >= 0.):
return r
else:
return 2. - r
def ncdf(x):
return 1. - 0.5*erfcc(x/(2**0.5))
在Unknown的例子基础上,许多库中实现的函数normdist()的Python等效函数如下:
def normcdf(x, mu, sigma):
t = x-mu;
y = 0.5*erfcc(-t/(sigma*sqrt(2.0)));
if y>1.0:
y = 1.0;
return y
def normpdf(x, mu, sigma):
u = (x-mu)/abs(sigma)
y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2)
return y
def normdist(x, mu, sigma, f):
if f:
y = normcdf(x,mu,sigma)
else:
y = normpdf(x,mu,sigma)
return y
Taken from above:
from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435
对于双尾检验:
最初的回答:
Import numpy as np
z = 1.96
p_value = 2 * norm.cdf(-np.abs(z))
0.04999579029644087
就像这样简单:
import math
def my_cdf(x):
return 0.5*(1+math.erf(x/math.sqrt(2)))
help(norm.ppf)
,但是“loc”和“scale”到底是什么意思 - 需要帮助理解帮助文档。 - WestCoastProjects