9

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

Pi_
  • 2,010
  • 5
  • 22
  • 24

2 Answers2

12

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.

DSM
  • 342,061
  • 65
  • 592
  • 494
  • Thanks, decimal does what I needed :) – Pi_ Oct 29 '12 at 02:38
  • I could not recast to stay in the log space as I am working with log a and log b and need a / (a + b) which would require log(a + b) which isn't trivial in obtaining when having only log a and log b. – Pi_ Oct 29 '12 at 02:42
4

Try calculating in logarithmic domain as long as possible. I.e. avoid calculating the exact value but keep working with exponents.

exp(-1200) IS a very very small number (just as exp(1200) is a very very big one), so maybe the exact value is not really what you are interested in. If you only need to compare these numbers then logarithmic space should be enough.

astraujums
  • 709
  • 8
  • 20
  • Thanks for your input. I need absolute precision to standardize two such values; e.g. I need e^(log a)/(e^(log a) + e^log(b)), as to why I have log a and log b in the first place it is because I used a sum of logs as opposed to a product which was very, very, big. – Pi_ Oct 29 '12 at 02:37
  • 1
    @Pi_: umm, isn't `e^(log a)/(e^(log a) + e^log(b))` simply `a/(a+b)`? – DSM Oct 29 '12 at 02:40
  • @astraujums yes but I do not have a and b. I only have log a and log b which happen to be as small or smaller than -1200 – Pi_ Oct 29 '12 at 02:43
  • 2
    @Pi_ `e^(log a)/(e^(log a) + e^log(b))=1/(1+e^(log(b)-log(a)))`. – Teepeemm Oct 07 '15 at 12:07