39

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

1-math.exp(-4*1000000*-0.0641515994108)
Harpal
  • 12,057
  • 18
  • 61
  • 74
  • 2
    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 Oct 29 '10 at 10:22

6 Answers6

42

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.

Glenn Maynard
  • 55,829
  • 10
  • 121
  • 131
28

To fix it use:

try:
    ans = math.exp(200000)
except OverflowError:
    ans = float('inf')
DoOrDoNot
  • 1,132
  • 1
  • 10
  • 22
5

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.

Frits
  • 7,341
  • 10
  • 42
  • 60
MAK
  • 26,140
  • 11
  • 55
  • 86
4

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.

Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
4

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))
mpetric
  • 103
  • 7
4

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/

anonymous
  • 49
  • 1
  • 1
  • Here you can find the expo() method https://mpmath.org/doc/current/functions/powers.html#exponentiation – pyjavo Mar 01 '22 at 16:43