0

I have a function that is y = ax + b where a and b are constants. I want to find out the maximum value of y. We know that if a = 0 then y = b, otherwise the maximum value of y is infinity. So I tried to use scipy.interpolate.interp1d to get the answer. Running the example 2 below will result in an error message.

from scipy import interpolate
import math

# example 1 (works): y = x + 0
func1 = interpolate.interp1d([1,2], [1,2], fill_value='extrapolate')
print(func1(math.inf)) # this will print inf as expected

# example 2 (doesn't work): y = 1
func2 = interpolate.interp1d([1,2], [1,1], fill_value='extrapolate')
print(func2(math.inf)) # I'm expecting 1, however it showed array(nan)

Error message:

RuntimeWarning: invalid value encountered in multiply
  y_new = slope*(x_new - x_lo)[:, None] + y_lo

Edit: Replacing math.inf with a very large number, like func2(9223372036854775807) works too.

cf1
  • 67
  • 4
  • The problem is not that `interp1d` cannot handle an infinite number. You disproved that in the first case, which worked just fine. The issue is that the line has a slope of 0. It's asymptotic in x. There's no way for it to choose new points to extrapolate. I'd argue that this is a case of "Don't Do That". – Tim Roberts May 05 '21 at 20:27
  • Please see my edit regarding slope of 0 – cf1 May 05 '21 at 20:36

1 Answers1

3

This is due to rules for doing arithmetic with inf as defined in the the IEEE 754 standard. The rules are:

  1. For any x > 0, we have x * inf -> inf
  2. 0 * inf = nan
  3. For any x < 0, we have x * inf -> -inf

The reasons for rule 2 are discussed elsewhere.

If we inspect the line of code from your error message we can figure out what is going on:

y_new = slope * (x_new - x_lo)

The term in brackets has the value inf for both of your examples. In you first example slope = 1 so we apply the first rule and get 1 * inf -> inf. However, in your second example slope = 0 so we have to use the second rule and we get 0 * inf -> nan.

myrtlecat
  • 2,156
  • 12
  • 16