Python: OverflowError: math range error

Cause of Python: OverflowError: math range error

This error Python: OverflowError: math range error of python can get while working with the math module in python. This overflow error comes when the output generated by the function is not in the range of the function. The code for the above error is shown below as an example.

 

import math
1-math.exp(-4*1000000*-0.0641515994108)

 

The screenshot of the error is also shown below for your reference. 

 

 

Solution

The main error in the above code is that the amount you want math.exp to calculate includes more than 110,000 decimal digits. That results in an overflow because it is just barely beyond a double range. 

To solve this issue one can try the code as shown below:

 

# trying the function value in the try block
try:
    answer = math.exp(200000)

# code if the try block do not work 
except OverflowError:
    answer = float('inf')
print(answer)

Output 

 

The highest figure for which one can compute the machine’s experience in Python is only a little greater than 709.78271.

Apart from this solution, one can also use mpmath library of python. To use this library one need to write this line at the top of their code. 

from mpmath import *

As a last solution, one can also use np.exp() function of python instead of math.exp(). Np.exp(999) returns inf because Numpy handles overflows more gracefully, while 1. / (1. + np.exp(999)) just returns zero.

The code for the last one is as follows:

 

import math 
import numpy as np

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

Output

 

 

Also Read: Prediction using Lasso and Ridge Regression

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *