jsh*_*py8 5 python numpy spline scipy
我正在通过一组给定的数据点生成三次样条图:
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
x = np.array([1, 2, 4, 5]) # sort data points by increasing x value
y = np.array([2, 1, 4, 3])
arr = np.arange(np.amin(x), np.amax(x), 0.01)
s = interpolate.CubicSpline(x, y)
plt.plot(x, y, 'bo', label='Data Point')
plt.plot(arr, s(arr), 'r-', label='Cubic Spline')
plt.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)
如何从中获得样条方程式CubicSpline?我需要以下形式的方程式:

我尝试了各种方法来获取系数,但是它们都使用通过不同数据获得的数据,而不仅仅是数据点。
从文档中:
c (ndarray, shape (4, n-1, ...)) 每段多项式的系数。尾部尺寸与 的尺寸匹配
y,不包括轴。例如,如果y是 1-d,则是和 之间段上的c[k, i]系数。(x-x[i])**(3-k)x[i]x[i+1]
因此,在您的示例中,第一段[x 1 , x 2 ]的系数将位于第 0 列中:
s.c[3, 0]s.c[2, 0]s.c[1, 0]s.c[0, 0]。然后,对于第二段[x 2 , x 3 ],您将有s.c[3, 1], s.c[2, 1], s.c[1, 1],s.c[0, 1]对于y 2,b 2,c 2,d 2,依此类推。
例如:
x = np.array([1, 2, 4, 5]) # sort data points by increasing x value
y = np.array([2, 1, 4, 3])
arr = np.arange(np.amin(x), np.amax(x), 0.01)
s = interpolate.CubicSpline(x, y)
fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(x, y, 'bo', label='Data Point')
ax.plot(arr, s(arr), 'k-', label='Cubic Spline', lw=1)
for i in range(x.shape[0] - 1):
segment_x = np.linspace(x[i], x[i + 1], 100)
# A (4, 100) array, where the rows contain (x-x[i])**3, (x-x[i])**2 etc.
exp_x = (segment_x - x[i])[None, :] ** np.arange(4)[::-1, None]
# Sum over the rows of exp_x weighted by coefficients in the ith column of s.c
segment_y = s.c[:, i].dot(exp_x)
ax.plot(segment_x, segment_y, label='Segment {}'.format(i), ls='--', lw=3)
ax.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2889 次 |
| 最近记录: |