2

I'm trying to use interp1d() from scipy to interpolate some data, but I keep hitting an out or range error. After hours of Googling, I now know that x values not in increasing order will cause the same error I'm getting but I've already made sure that's not the problem. As far as I can tell, it looks like interp1d() doesn't like decimals in the first value. Am I missing something?

A simplified version of my problem:

The following runs just fine.

import numpy as np
from scipy.interpolate import interp1d

interp1d(np.array([1, 2, 3, 4, 5, 6]),
         np.array([2, 4, 6, 8, 10, 12]), kind='cubic')(np.linspace(1, 6, num=40))

But, this:

interp1d(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6]),
     np.array([2, 4, 6, 8, 10, 12]), kind='cubic')(np.linspace(1, 6, num=40))

Returns:

ValueError: A value in x_new is below the interpolation range.

But, this works just fine.

interp1d(np.array([1.0, 2.2, 3.3, 4.4, 5.5, 6.6]),
         np.array([2, 4, 6, 8, 10, 12]), kind='cubic')(np.linspace(1, 6, num=40))
CircleSquared
  • 379
  • 2
  • 11

1 Answers1

12

inter1d returns a function which allows you to interpolate within the domain of the data. When you use

interp1d(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6]),
     np.array([2, 4, 6, 8, 10, 12]), kind='cubic')(np.linspace(1, 6, num=40))

the domain of the data is the interval [1.1, 6.6], the minimum to maximum values of the x-values.

Since 1 is in np.linspace(1, 6, num=40) and 1 lies outside [1.1, 6.6], interp1d raises

ValueError: A value in x_new is below the interpolation range.

when you try to interpolate the data at the x-values np.linspace(1, 6, num=40).

When you change the x-values of the data to

np.array([1.0, 2.2, 3.3, 4.4, 5.5, 6.6])

then the domain of the data is expanded to [1.0, 6.6], which now includes 1. Hence, interpolating at np.linspace(1, 6, num=40) now works.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    Thank you very much. It took my dense brain a few passes to get it, but I realized from your explanation that I had it backwards. I was trying to fit the wrong range inside of the other. I thought the old x values needed to fit within the range produced by linspace(), not the other way around. – CircleSquared May 15 '15 at 04:59