Does scipy.interpolate.interp1d have problems with decimal values leading the x values?

戏子无情 提交于 2019-12-07 20:55:52

问题


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))

回答1:


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.



来源:https://stackoverflow.com/questions/30244888/does-scipy-interpolate-interp1d-have-problems-with-decimal-values-leading-the-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!