overflow – OverflowError: long int too large to convert to float in python

overflow – OverflowError: long int too large to convert to float in python

Factorials get large real fast:

>>> math.factorial(170)

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

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

but the next factorial is too large:

>>> float(math.factorial(171))
Traceback (most recent call last):
  File <stdin>, line 1, in <module>
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))

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

When idx gets large either the math.pow and/or the math.factorial will become insanely large and be unable to convert to a floating value (idx=1000 triggers the error on my 64 bit machine). Youll want to not use the math.pow function as it overflows earlier than the built in ** operator because it tries to keep higher precision by float converting earlier. Additionally, you can wrap each function call in a Decimal object for higher precision.

Another approach when dealing with very large numbers is to work in the log scale. Take the log of every value (or calculate the log version of each value) and perform all required operations before taking the exponentiation of the results. This allows for your values to temporary leave the floating domain space while still accurately computing a final answer that lies within floating domain.

3 ** idx  =>  math.log(3) * idx
math.exp(-3) * p  =>  -3 + math.log(p)
math.factorial(idx)  =>  sum(math.log(ii) for ii in range(1, idx + 1))

This stays in the log domain until the very end so your numbers can get very, very large before youll hit overflow problems.

overflow – OverflowError: long int too large to convert to float in python

Try using the decimal library. It claims to support arbitrary precision.
from decimal import Decimal

Also, you dont need to use math.pow. pow is in-built.

Leave a Reply

Your email address will not be published. Required fields are marked *