Search code examples
pythonmathexponentialunderflow

Exponential of very small number in python


I am trying to calculate the exponential of -1200 in python (it's an example, I don't need -1200 in particular but a collection of numbers that are around -1200).

>>> math.exp(-1200)
0.0

It is giving me an underflow; How may I go around this problem?

Thanks for any help :)


Solution

  • In the standard library, you can look at the decimal module:

    >>> import decimal
    >>> decimal.Decimal(-1200)
    Decimal('-1200')
    >>> decimal.Decimal(-1200).exp()
    Decimal('7.024601888177132554529322758E-522')
    

    If you need more functions than decimal supports, you could look at the library mpmath, which I use and like a lot:

    >>> import mpmath
    >>> mpmath.exp(-1200)
    mpf('7.0246018881771323e-522')
    >>> mpmath.mp.dps = 200
    >>> mpmath.exp(-1200)
    mpf('7.0246018881771325545293227583680003334372949620241053728126200964731446389957280922886658181655138626308272350874157946618434229308939128146439669946631241632494494046687627223476088395986988628688095132e-522')
    

    but if possible, you should see if you can recast your equations to work entirely in the log space.