Skip to content Skip to sidebar Skip to footer

Python E**(-x) Overflowerror: (34, 'result Too Large')

Is there a way in python to truncate the decimal part at 5 or 7 digits? If not, how can i avoid a float like e**(-x) number to get too big in size? Thanks

Solution 1:

Either catch the OverflowError or use the decimal module. Python is not going to assume you were okay with the overflow.

>>> 0.0000000000000000000000000000000000000000000000000000000000000001**-30
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
>>> d = decimal.Decimal(0.0000000000000000000000000000000000000000000000000000000000000001)
>>> d**-30Decimal('1.000000000000001040827834994E+1920')

Solution 2:

The "Result too large" doesn't refer to the number of characters in the decimal representation of the number, it means that the number that resulted from your exponential function is large enough to overflow whatever type python uses internally to store floating point values.

You need to either use a different type to handle your floating point calculations, or rework you code so that e**(-x) doesn't overflow or underflow.

Solution 3:

this seems to work

fromdecimal import *
getcontext().prec =7
math.exp(-Decimal(x))

Post a Comment for "Python E**(-x) Overflowerror: (34, 'result Too Large')"