我试图计算并绘制两个列表x和y的数值导数(dy / dx)。我使用scipy.interpolate.UnivariateSpline和scipy.interpolate.UnivariateSpline.derivative来计算斜率。 y对x的曲线似乎是C1连续的,并且我期望斜率dy / dx在对x绘制时也是平滑的。但那么是什么原因导致情节中的小凹凸呢?还有关于如何按摩代码使其连续C1的任何建议吗?
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline
x=[20.14141131550861, 20.29161104293003, 20.458574567775457, 20.653802880772922, 20.910446090013004, 21.404599384233677, 21.427939384233678, 21.451279384233676, 21.474619384233677, 21.497959384233678, 21.52129938423368, 21.52130038423368, 21.54463938423368, 21.56797938423368, 21.59131938423368, 21.61465938423368, 21.63799938423368, 22.132152678454354, 22.388795887694435, 22.5840242006919]
y=[-1.6629252348586834, -1.7625046339166028, -1.875358801338162, -2.01040013818419, -2.193327440415778, -2.5538174545988306, -2.571799827167608, -2.5896274995868005, -2.607298426787476, -2.624811539182082, -2.642165776735291, -2.642165776735291, -2.659360089028171, -2.6763934353217587, -2.693264784620056, -2.7099731157324367, -2.7265165368570314, -3.0965791078676754, -3.290845721407758, -3.440799238587583]
spl1 = UnivariateSpline(x,y,s=0)
dydx = spl1.derivative(n=1)
T = dydx(x)
plt.plot(x,y,'-x')
plt.plot(x,T,'-')
plt.show()
答案 0 :(得分:2)
给定的数据点看起来像是一个很好的C1平滑曲线,但它们没有。绘制斜率(y与x的差值的差异)显示:
XYZY PC,PP,CC,CP
XZYY PC,CC,PP,CP or PC,CC,CP,PP
ZXYY CC,PC,PP,CP or CC,PC,CP,PP
ZYXY CC,CP,PC,PP
ZYYX CC,CP,PP,PC
数组中有一些重复的y值,它们看起来不属于x,也有一些近似重复(但不重复)的x值。
修复样条曲线的最简单方法是允许一点点平滑:
plt.plot(np.diff(y)/np.diff(x))
使衍生物符合您的预期:
删除“坏苹果”也有帮助,尽管没有那么多。
spl1 = UnivariateSpline(x, y, s=1e-5)