首页 > 解决方案 > python:使用 interp1d 用 scipy 插值因 kind=4 / 四阶失败

问题描述

我正在尝试使用interp1d函数在离散数据点之间进行插值scipy

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import numpy as np
import scipy
from scipy import interpolate
import matplotlib
import matplotlib.pyplot as plt

# ----- continuous function + sample data

x = np.linspace(1,40,15)
y = np.log(x)+0.5*np.sin(0.4*x)

xhi = np.linspace(1,40,10000)
yhi = np.log(xhi)+0.5*np.sin(0.4*xhi)

# ----- spline functions

f1 = scipy.interpolate.interp1d(x, y, kind=1)
yi1 = f1(xhi)

f2 = scipy.interpolate.interp1d(x, y, kind=2)
yi2 = f2(xhi)

f3 = scipy.interpolate.interp1d(x, y, kind=3)
yi3 = f3(xhi)

#f4 = scipy.interpolate.interp1d(x, y, kind=4) ## fails!!!
#yi4 = f4(xhi)

# ----- plot

plt.close('all')
fig1 = plt.figure(figsize=(1600/100,900/100))
plt.grid(which='major', axis='both', linestyle='--', linewidth=0.2, c='gray', alpha=0.5)
ax1 = fig1.gca()
ax1.plot( xhi, yhi, linestyle='--', linewidth=2.0, color='k', alpha=0.5, label=r'$\log(x)*0.5*\sin(0.4*x)$')
ax1.plot(xhi, yi1, linestyle='--', linewidth=1.0, color='blue', alpha=1.0, label='interp1d - O1')
ax1.plot(xhi, yi2, linestyle='--', linewidth=1.0, color='red', alpha=1.0, label='interp1d - O2')
ax1.plot(xhi, yi3, linestyle='--', linewidth=1.0, color='green', alpha=1.0, label='interp1d - O3')
#ax1.plot(xhi, yi4, linestyle='--', linewidth=1.0, color='purple', alpha=1.0, label='interp1d - O4') ## fails!!!
ax1.plot( x, y, marker='o', color='w', markeredgecolor='k', markersize=8.0, alpha=1.0, markeredgewidth=1.0, fillstyle='full', linestyle='none', label='interp pts')
ax1.legend(loc=4, fontsize='medium', ncol=1)
plt.show()

在此处输入图像描述

当我尝试将样条插值的顺序设置为 时kind=4,出现错误:

Traceback (most recent call last):
  File "./test.py", line 32, in <module>
    f4 = scipy.interpolate.interp1d(x, y, kind=4)
  File "/home/steve/anaconda3/lib/python3.7/site-packages/scipy/interpolate/interpolate.py", line 533, in __init__
    check_finite=False)
  File "/home/steve/anaconda3/lib/python3.7/site-packages/scipy/interpolate/_bsplines.py", line 790, in make_interp_spline
    t = _not_a_knot(x, k)
  File "/home/steve/anaconda3/lib/python3.7/site-packages/scipy/interpolate/_bsplines.py", line 583, in _not_a_knot
    raise ValueError("Odd degree for now only. Got %s." % k)
ValueError: Odd degree for now only. Got 4.

是否可以在一维中进行四阶 ( kind=4) 样条插值?scipy

标签: pythonpython-3.xscipyinterpolation

解决方案


我发布的问题太快了......似乎可以使用splrepand splev

f4 = scipy.interpolate.splrep(x, y, k=4)
yi4 = scipy.interpolate.splev(xhi, f4)

对于 1D 样条曲线使用的公式,我仍然有点好奇splrep/splev和之间的区别。interp1d


推荐阅读