三次样条的导数是二次样条。 SciPy 只有一个内置方法来查找三次样条的根。所以有两种方法:
- 使用 4 次样条进行插值,以便轻松找到其导数的根。
- 使用三次样条(通常更可取),并为其导数的根编写自定义函数。
我在下面描述了这两种解决方案。
4 次样条
使用InterpolatedUnivariateSpline.which 具有返回三次样条的.derivative 方法,可以应用.roots 方法。
from scipy.interpolate import InterpolatedUnivariateSpline
f = InterpolatedUnivariateSpline(x_axis, y_axis, k=4)
cr_pts = f.derivative().roots()
cr_pts = np.append(cr_pts, (x_axis[0], x_axis[-1])) # also check the endpoints of the interval
cr_vals = f(cr_pts)
min_index = np.argmin(cr_vals)
max_index = np.argmax(cr_vals)
print("Maximum value {} at {}\nMinimum value {} at {}".format(cr_vals[max_index], cr_pts[max_index], cr_vals[min_index], cr_pts[min_index]))
输出:
最大值 6.779687224066201 在 2.1824928509277037
最小值 0.34588448400295346 在 2.2075868177297036
三次样条
我们需要一个用于二次样条根的自定义函数。在这里(解释如下)。
def quadratic_spline_roots(spl):
roots = []
knots = spl.get_knots()
for a, b in zip(knots[:-1], knots[1:]):
u, v, w = spl(a), spl((a+b)/2), spl(b)
t = np.roots([u+w-2*v, w-u, 2*v])
t = t[np.isreal(t) & (np.abs(t) <= 1)]
roots.extend(t*(b-a)/2 + (b+a)/2)
return np.array(roots)
现在完全按照上面的方法进行,除了使用自定义求解器。
from scipy.interpolate import InterpolatedUnivariateSpline
f = InterpolatedUnivariateSpline(x_axis, y_axis, k=3)
cr_pts = quadratic_spline_roots(f.derivative())
cr_pts = np.append(cr_pts, (x_axis[0], x_axis[-1])) # also check the endpoints of the interval
cr_vals = f(cr_pts)
min_index = np.argmin(cr_vals)
max_index = np.argmax(cr_vals)
print("Maximum value {} at {}\nMinimum value {} at {}".format(cr_vals[max_index], cr_pts[max_index], cr_vals[min_index], cr_pts[min_index]))
输出:
最大值 6.782781181150518 在 2.1824928579767167
最小值 0.45017143148176136 在 2.2070746522580795
与第一种方法的输出略有差异不是错误; 4 度样条和 3 度样条有点不同。
quadratic_spline_roots的解释
假设我们知道二次多项式在 -1、0、1 处的值是 u、v、w。它在区间 [-1, 1] 上的根是什么?通过一些代数我们可以发现多项式是
((u+w-2*v) * x**2 + (w-u) * x + 2*v) / 2
现在可以使用二次公式,但最好使用np.roots,因为它也可以处理前导系数为零的情况。然后将根过滤为 -1 到 1 之间的实数。最后,如果区间是某个 [a, b] 而不是 [-1, 1],则进行线性变换。
奖励:三次样条曲线在中间范围的宽度
假设我们想要找到样条曲线在哪里取值等于其最大值和最小值的平均值(即它的中间值)。那么我们绝对应该使用三次样条进行插值,因为现在需要roots 方法。不能只做(f - mid_range).roots(),因为 SciPy 不支持向样条曲线添加常量。相反,从y_axis - mid_range 构建一个下移样条。
mid_range = (cr_vals[max_index] + cr_vals[min_index])/2
f_shifted = InterpolatedUnivariateSpline(x_axis, y_axis - mid_range, k=3)
roots = f_shifted.roots()
print("Mid-range attained from {} to {}".format(roots.min(), roots.max()))
从 2.169076230034363 到 2.195974299834667 达到中等范围