Posted on 2nd May 2025|753 views
How to resolve overflow error in python?
am using numpy.exp something like this
cc = np.array([ [0.130,0.14,-1334.1] ])
pIrint 1/(1+np.exp(-cc))
But this is showing an error like this
/usr/local/lib/python2.7/site-packages/ipykernel/__main__.py:5: RuntimeWarning: overflow encountered in exp
Posted on 2nd May 2025| views
Here is what you can try to resolve the error, use the decimal module that permits you to work with arbitrary precision floats. You can follow the below example where I am using a numpy array of floats with 100 digits
import numpy as np
import decimal
# use this precision
decimal.getcontext().prec = 100
# this is the Original array
cc = np.array( [0.130,0.14,-1334.1] )
# this Fails
print(1/(1 + np.exp(-cc)))
# New array with the specified precision
ccd = np.asarray([decimal.Decimal(el) for el in cc], dtype=object)
# this Works!
print(1/(1 + np.exp(-ccd)))