You need to enable JavaScript to run this app. 如何基于Numpy用Python从头实现自然三次样条的完整计算
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Numpy用Python从头实现自然三次样条的完整计算

自然三次样条(Natural Cubic Splines)Numpy实现

核心数学原理

我们首先有已知离散点集 $(x_0,y_0), (x_1,y_1), ..., (x_{n-1},y_{n-1})$,满足 $x_0 < x_1 < ... < x_{n-1}$,自然三次样条是满足以下约束的分段三次函数:

  1. 每个区间 $[x_i, x_{i+1}]$ 上的多项式形式为:
    $$S_i(x) = a_i + b_i(x-x_i) + c_i(x-x_i)^2 + d_i(x-x_i)^3$$
  2. 所有采样点处函数值连续:$S(x_i) = y_i$
  3. 所有内点处一阶、二阶导数连续:$S_i'(x_{i+1})=S_{i+1}'(x_{i+1})$、$S_i''(x_{i+1})=S_{i+1}''(x_{i+1})$
  4. 自然样条专属端点约束:$S''(x_0)=0$、$S''(x_{n-1})=0$

求解步骤

  1. 定义区间长度 $h_i = x_{i+1} - x_i$
  2. 构造三对角线性方程组求解各采样点的二阶导数值 $m_i = S''(x_i)$,方程组形式为:
    $$
    \begin{bmatrix}
    1 & 0 & & & \
    \mu_1 & 2 & \lambda_1 & & \
    & \ddots & \ddots & \ddots & \
    & & \mu_{n-2} & 2 & \lambda_{n-2} \
    & & & 0 & 1
    \end{bmatrix}
    \begin{bmatrix}
    m_0 \
    m_1 \
    \vdots \
    m_{n-2} \
    m_{n-1}
    \end{bmatrix}
    =
    \begin{bmatrix}
    0 \
    d_1 \
    \vdots \
    d_{n-2} \
    0
    \end{bmatrix}
    $$
    其中 $\mu_i = \frac{h_i}{h_{i-1}+h_i}$、$\lambda_i = 1 - \mu_i$、$d_i = \frac{6}{h_{i-1}+h_i}\left( \frac{y_{i+1}-y_i}{h_i} - \frac{y_i - y_{i-1}}{h_{i-1}} \right)$
  3. 求解得到$m_i$后,各分段多项式系数计算方式:
    $$
    \begin{align*}
    a_i &= y_i \
    b_i &= \frac{y_{i+1}-y_i}{h_i} - \frac{h_i(m_{i+1} + 2m_i)}{6} \
    c_i &= \frac{m_i}{2} \
    d_i &= \frac{m_{i+1} - m_i}{6h_i}
    \end{align*}
    $$

完整Python代码(Numpy实现)

import numpy as np

class NaturalCubicSpline:
    def __init__(self, x: np.ndarray, y: np.ndarray):
        """
        初始化自然三次样条拟合
        参数:
            x: 采样点x坐标,shape为(n,),要求严格递增
            y: 采样点y坐标,shape为(n,)
        """
        x = np.asarray(x).ravel()
        y = np.asarray(y).ravel()
        if x.shape[0] != y.shape[0] or x.shape[0] < 2:
            raise ValueError("x和y长度必须一致且至少包含2个点")
        if not np.all(np.diff(x) > 0):
            raise ValueError("x坐标必须严格递增")
        
        self.n = x.shape[0]
        self.x = x
        self.y = y
        
        # 计算区间长度h
        h = np.diff(x)
        
        # 构造三对角方程组的系数
        A = np.zeros((self.n, self.n))
        B = np.zeros(self.n)
        
        # 端点约束:二阶导数为0
        A[0, 0] = 1
        A[-1, -1] = 1
        B[0] = 0
        B[-1] = 0
        
        # 填充内点行
        for i in range(1, self.n-1):
            A[i, i-1] = h[i-1] / (h[i-1] + h[i])
            A[i, i] = 2
            A[i, i+1] = h[i] / (h[i-1] + h[i])
            B[i] = 6 * ( (y[i+1] - y[i])/h[i] - (y[i] - y[i-1])/h[i-1] ) / (h[i-1] + h[i])
        
        # 求解二阶导数m
        self.m = np.linalg.solve(A, B)
        
        # 预计算各分段系数
        self.a = y[:-1]
        self.b = (y[1:] - y[:-1])/h - h*(self.m[1:] + 2*self.m[:-1])/6
        self.c = self.m[:-1] / 2
        self.d = (self.m[1:] - self.m[:-1])/(6*h)
    
    def predict(self, x_pred: np.ndarray) -> np.ndarray:
        """
        预测指定x点的y值
        参数:
            x_pred: 待预测的x坐标,shape任意
        返回:
            y_pred: 对应预测的y值,shape和x_pred一致
        """
        x_pred = np.asarray(x_pred)
        orig_shape = x_pred.shape
        x_pred = x_pred.ravel()
        
        # 查找每个x_pred所属的区间
        idx = np.searchsorted(self.x, x_pred, side='right') - 1
        # 处理边界点等于x[-1]的情况
        idx[idx >= self.n - 1] = self.n - 2
        idx[idx < 0] = 0
        
        # 计算相对偏移
        dx = x_pred - self.x[idx]
        # 计算对应分段的y值
        y_pred = self.a[idx] + self.b[idx]*dx + self.c[idx]*dx**2 + self.d[idx]*dx**3
        
        return y_pred.reshape(orig_shape)

使用示例

import matplotlib.pyplot as plt

# 测试用采样点
x_sample = np.array([0, 1, 2, 3, 4, 5])
y_sample = np.array([0, 2, 1, 3, 2, 4])

# 拟合自然三次样条
spline = NaturalCubicSpline(x_sample, y_sample)

# 生成待预测的密集x点
x_pred = np.linspace(0, 5, 200)
y_pred = spline.predict(x_pred)

# 可视化结果
plt.scatter(x_sample, y_sample, c='red', label='采样点')
plt.plot(x_pred, y_pred, label='自然三次样条拟合曲线')
plt.legend()
plt.show()

内容的提问来源于stack exchange,提问作者Arty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 06:15:11