在给定均值和标准差的正态分布中,如何计算概率?

2024-04-25 12:58:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中计算正态分布中给定平均值的概率?我总是可以根据定义显式地编写自己的函数,就像这个问题中的OP一样:Calculating Probability of a Random Variable in a Distribution in Python

只是想知道是否有一个库函数调用将允许您这样做。在我的想象中,它是这样的:

nd = NormalDistribution(mu=100, std=12)
p = nd.prob(98)

Perl中有一个类似的问题:How can I compute the probability at a point given a normal distribution in Perl?。但是我在Python中没有看到一个

Numpy有一个random.normal函数,但它就像采样一样,不完全是我想要的


Tags: of函数in定义random概率variableperl
3条回答

Scipy.stats是一个很棒的模块。为了提供另一种方法,您可以直接使用

import math
def normpdf(x, mean, sd):
    var = float(sd)**2
    denom = (2*math.pi*var)**.5
    num = math.exp(-(float(x)-float(mean))**2/(2*var))
    return num/denom

这使用了这里的公式:http://en.wikipedia.org/wiki/Normal_distribution#Probability_density_function

要测试:

>>> normpdf(7,5,5)  
0.07365402806066466
>>> norm(5,5).pdf(7)
0.073654028060664664

这里是more info。 首先,您要处理一个冻结的分布(在本例中,冻结意味着其参数设置为特定值)。要创建冻结的分发,请执行以下操作:

import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)

#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability

#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function 
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%

#To find the variate for which the probability is given, let's say the 
#value which needed to provide a 98% probability, you'd use the 
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187

scipy.stats中有一个:

>>> import scipy.stats
>>> scipy.stats.norm(0, 1)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(0, 1).pdf(0)
0.3989422804014327
>>> scipy.stats.norm(0, 1).cdf(0)
0.5
>>> scipy.stats.norm(100, 12)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(100, 12).pdf(98)
0.032786643008494994
>>> scipy.stats.norm(100, 12).cdf(98)
0.43381616738909634
>>> scipy.stats.norm(100, 12).cdf(100)
0.5

[需要注意的一件事——只是一个提示——是参数传递有点广泛。由于代码的设置方式,如果您意外地编写了scipy.stats.norm(mean=100, std=12)而不是scipy.stats.norm(100, 12)scipy.stats.norm(loc=100, scale=12),那么它将接受它,但会默默地放弃这些额外的关键字参数,并为您提供默认值(0,1)。]

相关问题 更多 >

    热门问题