Python: OverflowError: math range error

后端 未结 6 685
轻奢々
轻奢々 2020-12-09 14:56

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

1-math.exp(-4*1000000*-0.0641515994108)
相关标签:
6条回答
  • 2020-12-09 15:36

    To fix it use:

    try:
        ans = math.exp(200000)
    except OverflowError:
        ans = float('inf')
    
    0 讨论(0)
  • 2020-12-09 15:43

    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.

    0 讨论(0)
  • 2020-12-09 15:49

    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))
    
    0 讨论(0)
  • 2020-12-09 15:55

    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.

    0 讨论(0)
  • 2020-12-09 15:55

    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/

    0 讨论(0)
  • 2020-12-09 15:59

    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.

    0 讨论(0)
提交回复
热议问题