Skip to main content
 首页 » 编程设计

python之stats.scipy.chi2 返回值 0.0

2025年05月04日17wayfarer

我正在尝试使用 scipy.stats.chi2.cdf 计算一些 p 值,如下所示。但是函数返回 0。

from scipy import stats 
1-stats.chi2.cdf(332.185545938, 18.8967858326) 
0.0 

有什么可以告诉我是否有另一个模块要使用,或者如果有一个我缺少的参数将允许它计算这么小的 p 值,我可以以某种方式设置代码以返回最小非零值吗P 值?

干杯

请您参考如下方法:

您可以改用生存函数 (1-cdf):

>>> from scipy import stats 
>>> 1 - stats.chi2.cdf(332.185545938, 18.8967858326) 
0.0 
>>> stats.chi2.sf(332.185545938, 18.8967858326) 
4.1718344487607692e-59 

我们可以使用解析 cdf 检查这个结果:

>>> import mpmath 
>>> mpmath.mp.dps = 100 
>>> def chi2_cdf(k,x): return mpmath.gammainc(x/2.0,0,k/2.0)/mpmath.gamma(x/2.0) 
>>> chi2_cdf(332.185545938, 18.8967858326) 
mpf('0.9999999999999999999999999999999999999999999999999999999999582816555123918223004416138082464542159504946') 
>>> float(1-_) 
4.171834448760817e-59