python - 溢出错误 : long int too large to convert to float in python

标签 python overflow factorial

我尝试在 python 中计算泊松分布如下:

p = math.pow(3,idx)
depart = math.exp(-3) * p 
depart = depart / math.factorial(idx)

idx 范围为 0

但我得到 OverflowError: long int too large to convert to float

我尝试将离开转换为 float 但没有结果。

最佳答案

因子变大真的很快:

>>> math.factorial(170)
7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000L

注意L; 170 的阶乘仍然可以转换为 float :

>>> float(math.factorial(170))
7.257415615307999e+306

但是下一个阶乘太大了:

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

可以使用 decimal module ;计算会更慢,但 Decimal() 类可以处理这种大小的阶乘:

>>> from decimal import Decimal
>>> Decimal(math.factorial(171))
Decimal('1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000')

您必须始终使用 Decimal() 值:

from decimal import *

with localcontext() as ctx:
    ctx.prec = 32  # desired precision
    p = ctx.power(3, idx)
    depart = ctx.exp(-3) * p 
    depart /= math.factorial(idx)

关于python - 溢出错误 : long int too large to convert to float in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16174399/

相关文章:

python - 循环速度优化

html - 表格单元格内的 CSS 100% 宽度滚动条 (overflow-x)

c - C 程序,可处理 3 位数字,但无法处理 5 位数字

vba - 阶乘函数返回平方数而不是阶乘

python - 尝试在 macOS 上使用 pip 安装任何东西,但无法安装

python - 将标题添加到我已抓取的表格中

python - TensorFlow 2.0 : Eager execution of training either returns bad results or doesn't learn at all

当溢出可见时,CSS 自动高度不会拉伸(stretch)

使用 gcc 捕获类型转换溢出

algorithm - 用递归函数返回