使用Python进行样条插值

Hel*_*ish 11 python interpolation spline cubic

我编写了以下代码来执行样条插值:

import numpy as np
import scipy as sp

x1 = [1., 0.88,  0.67,  0.50,  0.35,  0.27, 0.18,  0.11,  0.08,  0.04,  0.04,  0.02]
y1 = [0., 13.99, 27.99, 41.98, 55.98, 69.97, 83.97, 97.97, 111.96, 125.96, 139.95, 153.95]

x = np.array(x1)
y = np.array(y1)

new_length = 25
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)
Run Code Online (Sandbox Code Playgroud)

但我得到了:

ValueError: A value in x_new is below the interpolation range.
Run Code Online (Sandbox Code Playgroud)

interpolate.py

任何帮助,将不胜感激.

cif*_*key 13

scipy.interpolate.interp1d上scipy文档:

scipy.interpolate.interp1d(x,y,kind ='linear',axis = -1,copy = True,bounds_error = True,fill_value = np.nan)

x:array_like.单调递增实数值的一维数组.

...

问题是x值不是单调增加的.事实上,它们是单调递减的.让我知道这是否有效,如果它仍然是你正在寻找的计算:

import numpy as np
import scipy as sp
from scipy.interpolate import interp1d

x1 = sorted([1., 0.88, 0.67, 0.50, 0.35, 0.27, 0.18, 0.11, 0.08, 0.04, 0.04, 0.02])
y1 = [0., 13.99, 27.99, 41.98, 55.98, 69.97, 83.97, 97.97, 111.96, 125.96, 139.95, 153.95]

new_length = 25
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)
Run Code Online (Sandbox Code Playgroud)

  • 在此示例中,仅通过对x1数组进行排序来破坏x1,y​​1对.应该以与x1数组相同的方式对y1数组进行混洗. (9认同)
  • 你可以使用`x1.reverse()`和`y1.reverse()`而不是`sorted()`. (4认同)

Mar*_*oma 11

您可以通过以下方式获得此信息:

import numpy as np
import scipy as sp
from scipy.interpolate import interp1d

x1 = [1., 0.88,  0.67,  0.50,  0.35,  0.27, 0.18,  0.11,  0.08,  0.04,  0.04,  0.02]
y1 = [0., 13.99, 27.99, 41.98, 55.98, 69.97, 83.97, 97.97, 111.96, 125.96, 139.95, 153.95]

# Combine lists into list of tuples
points = zip(x1, y1)

# Sort list of tuples by x-value
points = sorted(points, key=lambda point: point[0])

# Split list of tuples into two list of x values any y values
x1, y1 = zip(*points)

new_length = 25
new_x = np.linspace(min(x1), max(x1), new_length)
new_y = sp.interpolate.interp1d(x1, y1, kind='cubic')(new_x)
Run Code Online (Sandbox Code Playgroud)

  • 使用上面的代码,我在最后一行中使用Python 3.6得到了这个错误:`ValueError:Expect x是一个有序的array_like. (3认同)