python中float转int出错_OverflowError:long int太大,无法在python中转换为float

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 ranges from 0

But I got OverflowError: long int too large to convert to float

I tried to convert depart to float but no results.

解决方案

Factorials get large real fast:

>>> math.factorial(170)

7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000L

Note the L; the factorial of 170 is still convertable to a float:

>>> float(math.factorial(170))

7.257415615307999e+306

but the next factorial is too large:

>>> float(math.factorial(171))

Traceback (most recent call last):

File "", line 1, in

OverflowError: long int too large to convert to float

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')

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值