我正在尝试使用scipy
中的interp1d
函数在离散数据点之间进行插值。
#!/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.
是否可以在1D的scipy
中进行四阶(kind=4
)样条插值?
发布于 2020-02-12 00:47:15
我发的问题太快了.使用splrep
和splev
似乎是可能的
f4 = scipy.interpolate.splrep(x, y, k=4)
yi4 = scipy.interpolate.splev(xhi, f4)
我仍然对splrep
/ splev
和interp1d
在用于一维样条线的公式方面的区别感到有点好奇。
https://stackoverflow.com/questions/60173598
复制相似问题