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.
Try using the decimal library. It claims to support arbitrary precision.
from decimal import Decimal
Also, you don't need to use
math.pow
.pow
is in-built.The
scipy
module could help you.scipy.misc.factorial is a factorial function that can use the gamma function approximation to calculate the factorial, and returns the result using floating points.
Gives:
There is also a module to calculate Poisson distributions. For example:
Gives:
Factorials get large real fast:
Note the
L
; the factorial of 170 is still convertable to a float:but the next factorial is too large:
You could use the
decimal
module; calculations will be slower, but theDecimal()
class can handle factorials this size:You'll have to use
Decimal()
values throughout:When
idx
gets large either themath.pow
and/or themath.factorial
will become insanely large and be unable to convert to a floating value (idx=1000
triggers the error on my 64 bit machine). You'll 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 aDecimal
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.
This stays in the log domain until the very end so your numbers can get very, very large before you'll hit overflow problems.