Skip to main content
 首页 » 编程设计

python之溢出错误 : . .long int 太大

2025年05月04日15lori

import math 
a = 100 
b = 110 
e = 2.71828 
x = (e**-a)*(a**b)/math.factorial(b) 
print round(x, 5) 

当 a 和 b 很大时,我收到此消息:

Traceback (most recent call last): 
  File "<stdin>", line 5, in <module> 
OverflowError: long int too large to convert to float 

请您参考如下方法:

您似乎在尝试实现泊松分布。对于较大的均值,它可以很好地近似于高斯分布,为此您不需要计算阶乘(正如其他人所说,阶乘太大了)。

http://en.wikipedia.org/wiki/Poisson_distribution#Related_distributions

编辑:事件数 k 与平均值无关,但通常人们不希望小 L 的概率如 P(200|L),或者将其四舍五入为零。

另请查看 Scipy 的实现,它似乎使用对数,另一种方式或避免非常大的数字: https://github.com/scipy/scipy/blob/v0.14.0/scipy/stats/_discrete_distns.py

编辑:因为有人要求,一个 R 中的演示(因为在我当前的设置中它对我来说更快,但数学是相同的)。我采用了 lambda = mean = sigma^2 = 500(没有对 n<1000 进行连续性校正):

pois = rpois(1000, 500) 
norm = rnorm(1000, 500, sqrt(500)) 
plot(density(pois)) 
lines(density(norm))