RuntimeWarning: overflow encountered in np.exp(x**2)

AKG picture AKG · Jul 8, 2014 · Viewed 15.8k times · Source

I need to calculate exp(x**2) where x = numpy.arange(30,90). This raises the warning:

RuntimeWarning: overflow encountered in exp
inf

I cannot safely ignore this warning, but neither SymPy nor mpmath is a solution and I need to perform array operations so a Numpy solution would be my dream.

Does anyone know how to handle this problem?

Answer

Gareth Rees picture Gareth Rees · Jul 8, 2014

You could use a data type that has the necessary range, for example decimal.Decimal:

>>> import numpy as np
>>> from decimal import Decimal
>>> x = np.arange(Decimal(30), Decimal(90))
>>> y = np.exp(x ** 2)
>>> y[-1]
Decimal('1.113246031563799750400684712E+3440')

But what are you using these numbers for? Could you avoid the exponentiation and work with logarithms? More detail about your problem would be helpful.