OverflowError:long int太大,无法在python中转换为float [英] OverflowError: long int too large to convert to float in python

查看:2239
本文介绍了OverflowError:long int太大,无法在python中转换为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to calculate poisson distribution in python as below:

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,但没有结果.

I tried to convert depart to float but no results.

推荐答案

工厂迅速发展壮大

>>> math.factorial(170)
7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000L

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

Note the L; the factorial of 170 is still convertable to a 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模块;计算会比较慢,但是Decimal()类可以处理以下大小的阶乘:

You could use the decimal module; calculations will be slower, but the Decimal() class can handle factorials this size:

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

您必须在整个过程中使用Decimal()值:

You'll have to use Decimal() values throughout:

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)

这篇关于OverflowError:long int太大,无法在python中转换为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆