python - 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
解决方案
我发布的问题太快了......似乎可以使用splrep
and splev
:
f4 = scipy.interpolate.splrep(x, y, k=4)
yi4 = scipy.interpolate.splev(xhi, f4)
对于 1D 样条曲线使用的公式,我仍然有点好奇splrep
/splev
和之间的区别。interp1d
推荐阅读
- python - ChromeDriver 上的 Time.sleep()
- python - Python/Pandas:如果值为 NaN 或 0,则使用同一行中下一列的值填充
- angular - Ngx-Bootstrap 和 Angular 9 ModuleWithProviders 错误
- python - Gimp Python 脚本未显示在菜单中
- lc3 - 您将如何编写代码以在用户输入的 2 个值之间添加每 4 个数字?
- python - Python聊天机器人项目上的Tensorflow错误
- javascript - 动态检查复选框是否被即时选中
- python - 如何在linux ubuntu终端上安装python3.9?
- sql - 检查每个值的数据类型的存储过程
- php - 从 SELECT 获取结果,然后将其更新到数据库 MySQL 和 PHP