34
votes

I get a Overflow error when i try this calculation, but i cant figure out why.

1-math.exp(-4*1000000*-0.0641515994108)
6
It's taking forever to calculate the math.exp of your expression in linux calc - actually around 3 minutes on my PC. The output didn't fit on screen, but here's the last part of it: 72601064848030549330052235283692208900018564830019400961030549300613573049038658490326003709885716700599883485335384987825755170505520081515667880006364976728119694600659746416440802282624919298297947165561974790549306225384099033699937030324423057761382164874383992786304290520859618809208146480637711575173287535774531529104427355177803053295844887694582338200906830029698966101673406039727344889895537434766431106 - kovshenin

6 Answers

34
votes

The number you're asking math.exp to calculate has, in decimal, over 110,000 digits. That's slightly outside of the range of a double, so it causes an overflow.

23
votes

To fix it use:

try:
    ans = math.exp(200000)
except OverflowError:
    ans = float('inf')
5
votes

I think the value gets too large to fit into a double in python which is why you get the OverflowError. The largest value I can compute the exp of on my machine in Python is just sligthly larger than 709.78271.

3
votes

This may give you a clue why:

http://www.wolframalpha.com/input/?i=math.exp%28-4*1000000*-0.0641515994108%29

Notice the 111442 exponent.

2
votes

Unfortunately, no one explained what the real solution was. I solved the problem using:

from mpmath import *

You can find the documentation below:

http://mpmath.org/

1
votes

Try np.exp() instead of math.exp()

Numpy handles overflows more gracefully, np.exp(999) results in inf and 1. / (1. + np.exp(999)) therefore simply results in zero

import math 
import numpy as np

print(1-np.exp(-4*1000000*-0.0641515994108))