pythonnumpyerror-handlingfloating-point

Numpy error: underflow encountered in exp


I'm attempting to define a simple exponential and regardless of the numbers I put into the argument of the exponential I get the following:

FloatingPointError: underflow encountered in exp

The array I'm trying to define is as follows:

     time = np.arange(length)
     window = np.exp(-(time-512)**2/1000.0)

where length = 4096. I'm rather inexperienced with Python and saw a similar question was answered on here somewhere but I didn't really understand it. I should also note that this code ran before without a problem.


Solution

  • Break down what you're computing for the final element:

    temp1 = 4096 - 512
    temp2 = temp1**2
    temp3 = -temp2
    temp4 = temp3 / 1000.0
    

    temp4 is -12845.056

    Now, what happens when you try to take the natural anti-log of that number? What is the range of float values you're allowed in numpy?

    I believe you'll find that you just tried to make it too small. If this is an intermediate result in a computation, I suggest that you hold the number as a natural log until you can make it larger again. Alternately, research some packages to support extreme values, or multiply all your values by a scalar large enough to preserve accuracy.