Search code examples
pythonnumpyexp

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


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?


Solution

  • 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.