Jump to content

Cubic spline interpolation: Difference between revisions

From Wikibase
No edit summary
 
(10 intermediate revisions by 2 users not shown)
Line 1: Line 1:
'''Cubic spline interpolation''' is the process of finding a '''continuous and differentiable up to second degree''' function $C(x)$ consisting of a series of cubic functions $C_i(x)$ that for a definite set of datapoints $\{(x_i,y_i)| i\in [0,n], i \in \mathbb{N}\}$ satisfies $C(x_i)=y_i$.
'''Cubic spline interpolation''' is the process of finding a '''continuous and twice differentiable''' function $C(x)$ consisting of a series of cubic functions $C_i(x)$ that for a definite set of datapoints $\{(x_i,y_i)| i\in [0,n], i \in \mathbb{N}\}$ satisfies $C(x_i)=y_i$.


i.e., find
i.e., find
Line 5: Line 5:
$$
$$
C(x)=C_i(x),\, x_i \le x \le x_{i+1} \\
C(x)=C_i(x),\, x_i \le x \le x_{i+1} \\
C_i(x)=a_i(x-x_i)^3+b_i(x-x_i)^2+c_i(x-x_i)+d_i,\, \forall i\in [0,n-1], i \in \mathbb{N}\
C_i(x)=a_i(x-x_i)^3+b_i(x-x_i)^2+c_i(x-x_i)+d_i,\, \forall i\in [0,n-1], i \in \mathbb{N}\\
$$
$$


Line 12: Line 12:
$$
$$
C(x_i)=y_i,\, \forall \{(x_i,y_i)| i\in [0,n], i \in \mathbb{N}\} \tag{1} \\
C(x_i)=y_i,\, \forall \{(x_i,y_i)| i\in [0,n], i \in \mathbb{N}\} \tag{1} \\
C_i(x_{i+1})=C_{i+1}(x_{i+1})=y_{x+1},\,  \forall i \in [0,n-1], i \in \mathbb{N} \tag{2} \\
C_i(x_{i+1})=C_{i+1}(x_{i+1})=y_{i+1},\,  \forall i \in [0,n-1], i \in \mathbb{N} \tag{2} \\
\dot C_i(x_{i+1})=\dot C_{i+1}(x_{i+1}),\,  \forall i \in [0,n-2], i \in \mathbb{N} \tag{3} \\
\dot C_i(x_{i+1})=\dot C_{i+1}(x_{i+1}),\,  \forall i \in [0,n-2], i \in \mathbb{N} \tag{3} \\
\ddot C_i(x_{i+1})=\ddot C_{i+1}(x_{i+1}),\,  \forall i \in [0,n-2], i \in \mathbb{N} \tag{4} \\
\ddot C_i(x_{i+1})=\ddot C_{i+1}(x_{i+1}),\,  \forall i \in [0,n-2], i \in \mathbb{N} \tag{4} \\
Line 20: Line 20:


$$
$$
\begin{aligned} g_{i}(x) &=a_{i}\left(x-x_{i}\right)^{3}+b_{i}\left(x-x_{i}\right)^{2}+c_{i}\left(x-x_{i}\right)+d_{i} \tag{5} \\
C_{i}(x) &=a_{i}\left(x-x_{i}\right)^{3}+b_{i}\left(x-x_{i}\right)^{2}+c_{i}\left(x-x_{i}\right)+d_{i} \tag{5} \\
g_{i}^{\prime}(x) &=3 a_{i}\left(x-x_{i}\right)^{2}+2 b_{i}\left(x-x_{i}\right)+c_{i} \tag{6}\\ g_{i}^{\prime \prime}(x) &=6 a_{i}\left(x-x_{i}\right)+2 b_{i} \tag{7} \end{aligned}  
C_{i}^{\prime}(x) &=3 a_{i}\left(x-x_{i}\right)^{2}+2 b_{i}\left(x-x_{i}\right)+c_{i} \tag{6}\\ C_{i}^{\prime \prime}(x) &=6 a_{i}\left(x-x_{i}\right)+2 b_{i} \tag{7}  
$$
$$


From 1 and 5, $d_i=y_i,\, \forall i \in [0,n-1], i \in \mathbb{N}$,
From 1 and 5, $d_i=y_i,\, \forall i \in [0,n-1], i \in \mathbb{N}$,


Let $h_i=x_{i+1}-x_i$,\,  f_i=y_{i+1}-y_i$,
Let $h_i=x_{i+1}-x_i$, $f_i=y_{i+1}-y_i$,


then from 2 and 5, $a_{i} h_{i}^{3}+b_{i} h_{i}^{2}+c_{i} h_{i}=f_{i}\forall i \in [0,n-1], i \in \mathbb{N} \tag{8, n equations}$;
then from 2 and 5,


from 3 and 6, $3 a_{i} h_{i}^{2}+2 b_{i} h_{i}+c_{i}=c_{i+1}, ,\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{9, n-1 equations}$;
$$
a_{i} h_{i}^{3}+b_{i} h_{i}^{2}+c_{i} h_{i}=f_{i},\, \forall i \in [0,n-1], i \in \mathbb{N} \tag{8, n equations},
$$
 
from 3 and 6,
 
$$
3 a_{i} h_{i}^{2}+2 b_{i} h_{i}+c_{i}=c_{i+1},\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{9, n-1 equations}
$$
 
from 4 and 7,


from 4 and 7, $3 a_{i} h_{i}+b_{i}=b_{i+1} ,\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{10, n-1 equations}$.
$$
3 a_{i} h_{i}+b_{i}=b_{i+1} ,\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{10, n-1 equations}
$$


Notice there are $3n$ remaining degrees of freedom: $a_i,b_i,c_i\, \forall i \in [0,n-1], i \in \mathbb{N}$.
Since each successive derivative eliminates one variable family (first $d_i$, second $c_i$), a sensible strategy of solution would be substitution of variables, e.g., rewriting everything in terms of $b_i$.


To reduce the degrees of freedom, extend 10 up to $i=n-1$:
Notice one potential problem of this strategy is that $b_n$ remains undefined by 8-10. Since there are $3n$ remaining degrees of freedom: $a_i,b_i,c_i\, \forall i \in [0,n-1], i \in \mathbb{N}$, and only $3n-2$ equations, an additional condition on $b_n$ can be safely imposed by extending 10 up to $i=n-1$:


$$
$$
Line 45: Line 57:


$$
$$
a_{i}=\frac{1}{3 h_{i}}\left(b_{i+1}-b_{i}\right), ,\, \forall i \in [0,n-1], i \in \mathbb{N} \tag{11, n equations}
a_{i}=\frac{1}{3 h_{i}}\left(b_{i+1}-b_{i}\right),\, \forall i \in [0,n-1], i \in \mathbb{N} \tag{11, n equations}
$$
$$


Line 66: Line 78:
$$
$$


At this point, $n-1$ equations and $n+1$ degrees of freedom, $b_i,\, i \in [0,n+1], i \in \mathbb{N}$, remain. Therefore, two additional conditions are required for one particular solution.
At this point, there remains $n-1$ equations and $n+1$ degrees of freedom, $b_i,\, i \in [0,n], i \in \mathbb{N}$. Therefore, two additional conditions can be imposed to identify one particular solution.


A commonly accepted set of 2 additional conditions, known as the '''not-a-knot''' conditions, are:
A commonly accepted pair of additional conditions, nicknamed '''not-a-knot''', imposes


$$
$$
g_{0}^{\prime}\left(x_{0}\right)=\alpha, \quad g_{n-1}^{\prime}\left(x_{n}\right)=\beta . \nonumber
a_0=a_1, \qquad a_{n-2}=a_{n-1}.
$$
$$


Which requires $a_0=a_1$, $a_{n-2}=a_{n-1}$,
which coupled with 2 to 4 imposing continuity and twice differentiability at $x_1$ and at $x_{n-1}$, imposes effectively that $C_0=C_1$, $C_{n-2}=C_{n-1}$, i.e.,the first and last two cubic pieces become one, and points $(x_1,y_1)$ and $(x_{n-1},y_{n-1})$ stop being "knots" of the spline, hence the name. This smooths up the curves near the end-points.


From 11,
Using 11 on those additional conditions,


$$
$$
Line 97: Line 109:


$$
$$
\left(\begin{array}{cccccccc} h_1 & -(h_0+h_1) & h_0 & 0 & \cdots & 0 & 0 \\ \frac{1}{3} h_{0} & \frac{2}{3}\left(h_{0}+h_{1}\right) & \frac{1}{3} h_{1} & 0 & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ 0 & 0 & 0 & \cdots & \frac{1}{3} h_{n-2} & \frac{2}{3}\left(h_{n-2}+h_{n-1}\right) & \frac{1}{3} h_{n-1} \\ 0 & 0 & 0 & \cdots & h_{n-1} & -(h_{n-2}+h{n-1}) & h_{n-2}\end{array}\right)\left(\begin{array}{c} b_{0} \\ b_{1} \\ \vdots \\ b_{n-1} \\ b_{n} \end{array}\right)\left(\begin{array}{c} 0 \\ \frac{f_{1}}{h_{1}}-\frac{f_{0}}{h_{0}} \\ \vdots \\ \frac{f_{n-1}}{h_{n-1}}-\frac{f_{n-2}}{h_{n-2}} \\ 0 \end{array}\right)
\left(\begin{array}{ccccccc} h_1 & -(h_0+h_1) & h_0 & 0 & \cdots & 0 & 0 \\ \frac{1}{3} h_{0} & \frac{2}{3}\left(h_{0}+h_{1}\right) & \frac{1}{3} h_{1} & 0 & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ 0 & 0 & 0 & \cdots & \frac{1}{3} h_{n-2} & \frac{2}{3}\left(h_{n-2}+h_{n-1}\right) & \frac{1}{3} h_{n-1} \\ 0 & 0 & 0 & \cdots & h_{n-1} & -\left(h_{n-2}+h_{n-1}\right) & h_{n-2}\end{array}\right)\left(\begin{array}{c} b_{0} \\ b_{1} \\ \vdots \\ b_{n-1} \\ b_{n} \end{array}\right)=\left(\begin{array}{c} 0 \\ \frac{f_{1}}{h_{1}}-\frac{f_{0}}{h_{0}} \\ \vdots \\ \frac{f_{n-1}}{h_{n-1}}-\frac{f_{n-2}}{h_{n-2}} \\ 0 \end{array}\right)
$$
$$


Finally, solve the matrix numerically (e.g., with python) to obtain the interpolating curve.
Finally, solve the $(n+1)\times(n+1)$ system numerically, e.g., with the code below, to obtain $b_i,\, \forall i \in [0,n]$; then 11, 12, and $d_i=y_i$ give the remaining coefficients.<ref>{{#cite:Q2381}}</ref>
 
<syntaxhighlight lang="python" copy>
import numpy as np
 
def cubic_spline(x, y, additional_conditions="not-a-knot"):
    """Coefficients of the cubic spline interpolating (x[i], y[i]).
 
    additional_conditions can be "not-a-knot", "natural", or end slopes known by other methods (C'(x0),C'(xn)).
    Piece i is a[i]*(t-x[i])**3 + b[i]*(t-x[i])**2 + c[i]*(t-x[i]) + d[i].
    """
    x = np.asarray(x, dtype=float)
    y = np.asarray(y, dtype=float)
    n = len(x) - 1
    if n < 3:
        raise ValueError("at least 4 data points are required")
 
    h = np.diff(x)
    f = np.diff(y)
 
    A = np.zeros((n + 1, n + 1))        # one row per equation, one column per b[i]
    r = np.zeros(n + 1)
 
    for i in range(n - 1):              # (13), rows 2 to n
        A[i + 1, i]    = h[i] / 3
        A[i + 1, i + 1] = 2 * (h[i] + h[i + 1]) / 3
        A[i + 1, i + 2] = h[i + 1] / 3
        r[i + 1] = f[i + 1] / h[i + 1] - f[i] / h[i]
 
    if additional_conditions == "natural":                # zero curvature at both ends: b[0] = b[n] = 0
        A[0, 0] = A[n, n] = 1.0
    elif additional_conditions == "not-a-knot":            # (14)
        A[0, 0], A[0, 1], A[0, 2] = h[1], -(h[0] + h[1]), h[0]
        A[n, n - 2], A[n, n - 1], A[n, n] = h[n - 1], -(h[n - 2] + h[n - 1]), h[n - 2]
    else:                              # prescribed end slopes alpha, beta
        alpha, beta = additional_conditions
        A[0, 0], A[0, 1] = 2 * h[0] / 3, h[0] / 3
        r[0] = f[0] / h[0] - alpha
        A[n, n - 1], A[n, n] = h[n - 1] / 3, 2 * h[n - 1] / 3
        r[n] = beta - f[n - 1] / h[n - 1]
 
    b = np.linalg.solve(A, r)
    a = (b[1:] - b[:-1]) / (3 * h)                  # (11)
    c = f / h - h * (2 * b[:-1] + b[1:]) / 3        # (12)
    d = y[:-1]                                      # (5) at x = x[i]
    return x, a, b[:-1], c, d
 
 
def spline_eval(spline, t, deriv=0):
    """Value of the spline, or of its first three derivatives, at t."""
    x, a, b, c, d = spline
    t = np.asarray(t, dtype=float)
    i = np.clip(np.searchsorted(x, t, side="right") - 1, 0, len(a) - 1)
    dx = t - x[i]
    if deriv == 0:
        return a[i] * dx**3 + b[i] * dx**2 + c[i] * dx + d[i]
    if deriv == 1:
        return 3 * a[i] * dx**2 + 2 * b[i] * dx + c[i]
    if deriv == 2:
        return 6 * a[i] * dx + 2 * b[i]
    return 6 * a[i] * np.ones_like(dx)
 
 
def spline_integral(spline, lower_boundary, higher_boundary):
    """Exact integral of the spline from lower_boundary to higher_boundary."""
    x, a, b, c, d = spline
    edges = np.unique(np.concatenate(([lower_boundary, higher_boundary], x[(x > lower_boundary) & (x < higher_boundary)])))
    total = 0.0
    for u, v in zip(edges[:-1], edges[1:]):
        i = int(np.clip(np.searchsorted(x, 0.5 * (u + v), side="right") - 1, 0, len(a) - 1))
        s, w = u - x[i], v - u
        total += (a[i] * ((s + w)**4 - s**4) / 4 + b[i] * ((s + w)**3 - s**3) / 3
                  + c[i] * ((s + w)**2 - s**2) / 2 + d[i] * w)
    return total
</syntaxhighlight>
 
<blockquote>
'Not-a-knot' is far from the only pair of possible additional conditions. As seen, two other pairs are implemented in the code:


<!-- add general algorithm python code, defined as a function -->
* Natural: $b_0=0,\, b_n=0$, i.e., zero curvature at both ends
* Clamped, or end-slopes: if $\dot C(x_0),\, \dot C(x_n)$ can be known by other methods. (Passed as the tuple `(alpha, beta)` in the code)
</blockquote>


{{Hidden example}}
{{Hidden example}}
<!-- add real-world example, code (reusing functions defined above) and final interpolated graph -->
'''Velocity of a rocket.''' The upward velocity of a rocket is tabulated at six unevenly spaced times, $h_0 = 10$, $h_1, h_2 = 5$, $h_3 = 2.5$, $h_4 = 7.5\ \mathrm{s}$:<ref>{{#cite:Q2382}}</ref>
 
{| class="wikitable"
! $t$ (s) !! 0 !! 10 !! 15 !! 20 !! 22.5 !! 30
|-
! $v$ (m/s) !! 0 !! 227.04 !! 362.78 !! 517.35 !! 602.97 !! 901.67
|}
 
Using 'not-a-knot' cubic spline interpolation, what are the estimated velocity, the acceleration, and the displacement since launch at $t = 16\ \mathrm{s}$?
 
<syntaxhighlight lang="python" copy>
import matplotlib.pyplot as plt
 
t_data = np.array([0.0, 10.0, 15.0, 20.0, 22.5, 30.0])
v_data = np.array([0.0, 227.04, 362.78, 517.35, 602.97, 901.67])
 
spline = cubic_spline(t_data, v_data, additional_conditions="not-a-knot")
natural = cubic_spline(t_data, v_data, additional_conditions="natural")
 
print(spline_eval(spline, 16.0), "m/s")              # velocity at 16 s
print(spline_eval(spline, 16.0, deriv=1), "m/s^2")  # acceleration at 16 s
print(spline_integral(spline, 0.0, 16.0), "m")      # displacement since launch
 
t = np.linspace(t_data[0], t_data[-1], 601)
slopes = np.diff(v_data) / np.diff(t_data)
 
 
def cumulative(t, n=2001):
    """Trapezoidal integral of the piecewise linear interpolant, from launch to each t."""
    out = np.empty_like(t)
    for k, u in enumerate(t):
        grid = np.linspace(0.0, u, n)
        out[k] = np.trapz(np.interp(grid, t_data, v_data), grid)
    return out
 
 
fig, (top, middle, bottom) = plt.subplots(3, 1, sharex=True, figsize=(7.6, 9.8))
 
top.plot(t_data, v_data, "o", color="#c0392b", label="measured data")
top.plot(t, np.interp(t, t_data, v_data), "--", color="0.55", label="piecewise linear")
top.plot(t, spline_eval(natural, t), ":", color="#e67e22", label="natural cubic spline")
top.plot(t, spline_eval(spline, t), color="#1f4e79", label="not-a-knot cubic spline")
top.set_ylabel("velocity $v$ (m/s)")
 
middle.plot(t, spline_eval(spline, t, deriv=1), color="#1f4e79", label="not-a-knot cubic spline")
middle.plot(t, spline_eval(natural, t, deriv=1), ":", color="#e67e22", label="natural cubic spline")
middle.step(t_data, np.append(slopes, np.nan), where="post", color="0.55", label="piecewise linear")
middle.set_ylabel("acceleration $\\dot v$ (m/s$^2$)")
 
bottom.plot(t, cumulative(t), "--", color="0.55", label="piecewise linear (trapezoidal rule)")
bottom.plot(t, [spline_integral(natural, 0.0, u) for u in t], ":", color="#e67e22",
            label="natural cubic spline")
bottom.plot(t, [spline_integral(spline, 0.0, u) for u in t], color="#1f4e79",
            label="not-a-knot cubic spline")
bottom.set_xlabel("time $t$ (s)")
bottom.set_ylabel("displacement $s$ since launch (m)")
 
for ax in (top, middle, bottom):
    ax.grid(alpha=0.25)
    ax.legend(frameon=False, fontsize=9)
fig.tight_layout()
plt.show()
</syntaxhighlight>
 
[[File:Rocket velocity cubic spline.png|thumb|none|560px|alt=Three stacked line charts: velocity against time with the measured points, the piecewise linear interpolant and two cubic splines; below it the corresponding accelerations, and below that the displacement since launch|Velocity against time (top), the corresponding acceleration $\dot v$ (middle), and the displacement $s(t)=\int_0^t v\,\mathrm{d}\tau$ accumulated since launch (bottom). The acceleration of the cubic splines is continuous at every knot; that of the piecewise linear interpolant jumps.]]
 
$$
v(16) = 392.07\ \mathrm{m/s}, \qquad \dot{v}(16) = 29.67\ \mathrm{m/s^2}, \qquad s(16) = \int_{0}^{16} v(t)\,\mathrm{d}t = 2936.9\ \mathrm{m}.
$$
 
The cubic interpolant is compared with the piecewise and the natural cubic interpolants below.
 
{| class="wikitable"
|+ Estimates at $t = 16\ \mathrm{s}$, from three interpolants of the same six datapoints
! Method !! $v(16)$ (m/s) !! $\dot{v}(16)$ (m/s$^2$) !! $s(16)$ (m)
|-
! Piecewise linear
| 393.69 || 30.91 || 2987.99
|-
! Natural cubic spline
| 392.15 || 29.75 || 2947.40
|-
! Not-a-knot cubic spline
| 392.07 || 29.67 || 2936.88
|}
 
The velocity agrees between the three methods to within $1.6\ \mathrm{m/s}$, i.e., $0.4\%$. The integrated quantity is more sensitive: the displacement since launch varies by $51\ \mathrm{m}$ ($1.7\%$), so the choice of additional conditions must be made with care when an integral of the interpolant is the quantity of interest.
 
{{End hidden}}
{{End hidden}}
== References ==
<references/>

Latest revision as of 13:34, 28 October 2026

Languages: English · français · Esperanto

Cubic spline interpolation is the process of finding a continuous and twice differentiable function $C(x)$ consisting of a series of cubic functions $C_i(x)$ that for a definite set of datapoints $\{(x_i,y_i)| i\in [0,n], i \in \mathbb{N}\}$ satisfies $C(x_i)=y_i$.

i.e., find

$$\begin{gathered} C(x)=C_i(x),\, x_i \le x \le x_{i+1} \\ C_i(x)=a_i(x-x_i)^3+b_i(x-x_i)^2+c_i(x-x_i)+d_i,\, \forall i\in [0,n-1], i \in \mathbb{N}\\ \end{gathered}$$

so

$$\begin{gather} C(x_i)=y_i,\, \forall \{(x_i,y_i)| i\in [0,n], i \in \mathbb{N}\} \tag{1} \\ C_i(x_{i+1})=C_{i+1}(x_{i+1})=y_{i+1},\, \forall i \in [0,n-1], i \in \mathbb{N} \tag{2} \\ \dot C_i(x_{i+1})=\dot C_{i+1}(x_{i+1}),\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{3} \\ \ddot C_i(x_{i+1})=\ddot C_{i+1}(x_{i+1}),\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{4} \\ \end{gather}$$

Solution

$$\begin{gather} C_{i}(x) &=a_{i}\left(x-x_{i}\right)^{3}+b_{i}\left(x-x_{i}\right)^{2}+c_{i}\left(x-x_{i}\right)+d_{i} \tag{5} \\ C_{i}^{\prime}(x) &=3 a_{i}\left(x-x_{i}\right)^{2}+2 b_{i}\left(x-x_{i}\right)+c_{i} \tag{6}\\ C_{i}^{\prime \prime}(x) &=6 a_{i}\left(x-x_{i}\right)+2 b_{i} \tag{7} \end{gather}$$

From 1 and 5, $d_i=y_i,\, \forall i \in [0,n-1], i \in \mathbb{N}$,

Let $h_i=x_{i+1}-x_i$, $f_i=y_{i+1}-y_i$,

then from 2 and 5,

$$ a_{i} h_{i}^{3}+b_{i} h_{i}^{2}+c_{i} h_{i}=f_{i},\, \forall i \in [0,n-1], i \in \mathbb{N} \tag{8, n equations}, $$

from 3 and 6,

$$ 3 a_{i} h_{i}^{2}+2 b_{i} h_{i}+c_{i}=c_{i+1},\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{9, n-1 equations} $$

from 4 and 7,

$$ 3 a_{i} h_{i}+b_{i}=b_{i+1} ,\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{10, n-1 equations} $$

Since each successive derivative eliminates one variable family (first $d_i$, second $c_i$), a sensible strategy of solution would be substitution of variables, e.g., rewriting everything in terms of $b_i$.

Notice one potential problem of this strategy is that $b_n$ remains undefined by 8-10. Since there are $3n$ remaining degrees of freedom: $a_i,b_i,c_i\, \forall i \in [0,n-1], i \in \mathbb{N}$, and only $3n-2$ equations, an additional condition on $b_n$ can be safely imposed by extending 10 up to $i=n-1$:

$$ 3 a_{n-1} h_{n-1}+b_{n-1}=b_{n} $$

From 10,

$$ a_{i}=\frac{1}{3 h_{i}}\left(b_{i+1}-b_{i}\right),\, \forall i \in [0,n-1], i \in \mathbb{N} \tag{11, n equations} $$

Then use 11 to substitute for $a_i$ in 8,

$$ \begin{aligned} c_{i} &=\frac{1}{h_{i}}\left(f_{i}-a_{i} h_{i}^{3}-b_{i} h_{i}^{2}\right) \\ &=\frac{1}{h_{i}}\left(f_{i}-\frac{1}{3 h_{i}}\left(b_{i+1}-b_{i}\right) h_{i}^{3}-b_{i} h_{i}^{2}\right) \\ &=\frac{f_{i}}{h_{i}}-\frac{1}{3} h_{i}\left(b_{i+1}+2 b_{i}\right), \quad i=0 \text { to } n-1 . \end{aligned} \tag{12, n equations} $$

Now use 11,12 to substitute for $a_i$, $c_i$ in 9:

$$ \begin{gathered} 3\left(\frac{1}{3 h_{i}}\left(b_{i+1}-b_{i}\right)\right) h_{i}^{2}+2 b_{i} h_{i}+\left(\frac{f_{i}}{h_{i}}-\frac{1}{3} h_{i}\left(b_{i+1}+2 b_{i}\right)\right) \\ =\left(\frac{f_{i+1}}{h_{i+1}}-\frac{1}{3} h_{i+1}\left(b_{i+2}+2 b_{i+1}\right)\right) \end{gathered} $$

On simplification,

$$ \frac{1}{3} h_{i} b_{i}+\frac{2}{3}\left(h_{i}+h_{i+1}\right) b_{i+1}+\frac{1}{3} h_{i+1} b_{i+2}=\frac{f_{i+1}}{h_{i+1}}-\frac{f_{i}}{h_{i}} ,\, \forall i \in [0,n-2], i \in \mathbb{N} \tag{13, n-1 equations} $$

At this point, there remains $n-1$ equations and $n+1$ degrees of freedom, $b_i,\, i \in [0,n], i \in \mathbb{N}$. Therefore, two additional conditions can be imposed to identify one particular solution.

A commonly accepted pair of additional conditions, nicknamed not-a-knot, imposes

$$ a_0=a_1, \qquad a_{n-2}=a_{n-1}. $$

which coupled with 2 to 4 imposing continuity and twice differentiability at $x_1$ and at $x_{n-1}$, imposes effectively that $C_0=C_1$, $C_{n-2}=C_{n-1}$, i.e.,the first and last two cubic pieces become one, and points $(x_1,y_1)$ and $(x_{n-1},y_{n-1})$ stop being "knots" of the spline, hence the name. This smooths up the curves near the end-points.

Using 11 on those additional conditions,

$$ \begin{cases} \frac{1}{3 h_{0}}\left(b_{1}-b_{0}\right)=\frac{1}{3 h_{1}}\left(b_{2}-b_{1}\right) \\ \frac{1}{3 h_{n-2}}\left(b_{n-1}-b_{n-2}\right)=\frac{1}{3 h_{n-1}}\left(b_{n}-b_{n-1}\right). \end{cases} $$

On simplification,

$$ \begin{cases} h_{1} b_{0}-\left(h_{0}+h_{1}\right) b_{1}+h_{0} b_{2}=0 \\ h_{n-1} b_{n-2}-\left(h_{n-2}+h_{n-1}\right) b_{n-1}+h_{n-2} b_{n}=0. \end{cases} \tag{14, 2 equations} $$

Rewrite everything into matrices:

$$ \left(\begin{array}{ccccccc} h_1 & -(h_0+h_1) & h_0 & 0 & \cdots & 0 & 0 \\ \frac{1}{3} h_{0} & \frac{2}{3}\left(h_{0}+h_{1}\right) & \frac{1}{3} h_{1} & 0 & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ 0 & 0 & 0 & \cdots & \frac{1}{3} h_{n-2} & \frac{2}{3}\left(h_{n-2}+h_{n-1}\right) & \frac{1}{3} h_{n-1} \\ 0 & 0 & 0 & \cdots & h_{n-1} & -\left(h_{n-2}+h_{n-1}\right) & h_{n-2}\end{array}\right)\left(\begin{array}{c} b_{0} \\ b_{1} \\ \vdots \\ b_{n-1} \\ b_{n} \end{array}\right)=\left(\begin{array}{c} 0 \\ \frac{f_{1}}{h_{1}}-\frac{f_{0}}{h_{0}} \\ \vdots \\ \frac{f_{n-1}}{h_{n-1}}-\frac{f_{n-2}}{h_{n-2}} \\ 0 \end{array}\right) $$

Finally, solve the $(n+1)\times(n+1)$ system numerically, e.g., with the code below, to obtain $b_i,\, \forall i \in [0,n]$; then 11, 12, and $d_i=y_i$ give the remaining coefficients.[1]

import numpy as np

def cubic_spline(x, y, additional_conditions="not-a-knot"):
    """Coefficients of the cubic spline interpolating (x[i], y[i]).

    additional_conditions can be "not-a-knot", "natural", or end slopes known by other methods (C'(x0),C'(xn)).
    Piece i is a[i]*(t-x[i])**3 + b[i]*(t-x[i])**2 + c[i]*(t-x[i]) + d[i].
    """
    x = np.asarray(x, dtype=float)
    y = np.asarray(y, dtype=float)
    n = len(x) - 1
    if n < 3:
        raise ValueError("at least 4 data points are required")

    h = np.diff(x)
    f = np.diff(y)

    A = np.zeros((n + 1, n + 1))        # one row per equation, one column per b[i]
    r = np.zeros(n + 1)

    for i in range(n - 1):              # (13), rows 2 to n
        A[i + 1, i]     = h[i] / 3
        A[i + 1, i + 1] = 2 * (h[i] + h[i + 1]) / 3
        A[i + 1, i + 2] = h[i + 1] / 3
        r[i + 1] = f[i + 1] / h[i + 1] - f[i] / h[i]

    if additional_conditions == "natural":                 # zero curvature at both ends: b[0] = b[n] = 0
        A[0, 0] = A[n, n] = 1.0
    elif additional_conditions == "not-a-knot":            # (14)
        A[0, 0], A[0, 1], A[0, 2] = h[1], -(h[0] + h[1]), h[0]
        A[n, n - 2], A[n, n - 1], A[n, n] = h[n - 1], -(h[n - 2] + h[n - 1]), h[n - 2]
    else:                               # prescribed end slopes alpha, beta
        alpha, beta = additional_conditions
        A[0, 0], A[0, 1] = 2 * h[0] / 3, h[0] / 3
        r[0] = f[0] / h[0] - alpha
        A[n, n - 1], A[n, n] = h[n - 1] / 3, 2 * h[n - 1] / 3
        r[n] = beta - f[n - 1] / h[n - 1]

    b = np.linalg.solve(A, r)
    a = (b[1:] - b[:-1]) / (3 * h)                  # (11)
    c = f / h - h * (2 * b[:-1] + b[1:]) / 3        # (12)
    d = y[:-1]                                      # (5) at x = x[i]
    return x, a, b[:-1], c, d


def spline_eval(spline, t, deriv=0):
    """Value of the spline, or of its first three derivatives, at t."""
    x, a, b, c, d = spline
    t = np.asarray(t, dtype=float)
    i = np.clip(np.searchsorted(x, t, side="right") - 1, 0, len(a) - 1)
    dx = t - x[i]
    if deriv == 0:
        return a[i] * dx**3 + b[i] * dx**2 + c[i] * dx + d[i]
    if deriv == 1:
        return 3 * a[i] * dx**2 + 2 * b[i] * dx + c[i]
    if deriv == 2:
        return 6 * a[i] * dx + 2 * b[i]
    return 6 * a[i] * np.ones_like(dx)


def spline_integral(spline, lower_boundary, higher_boundary):
    """Exact integral of the spline from lower_boundary to higher_boundary."""
    x, a, b, c, d = spline
    edges = np.unique(np.concatenate(([lower_boundary, higher_boundary], x[(x > lower_boundary) & (x < higher_boundary)])))
    total = 0.0
    for u, v in zip(edges[:-1], edges[1:]):
        i = int(np.clip(np.searchsorted(x, 0.5 * (u + v), side="right") - 1, 0, len(a) - 1))
        s, w = u - x[i], v - u
        total += (a[i] * ((s + w)**4 - s**4) / 4 + b[i] * ((s + w)**3 - s**3) / 3
                  + c[i] * ((s + w)**2 - s**2) / 2 + d[i] * w)
    return total

'Not-a-knot' is far from the only pair of possible additional conditions. As seen, two other pairs are implemented in the code:

  • Natural: $b_0=0,\, b_n=0$, i.e., zero curvature at both ends
  • Clamped, or end-slopes: if $\dot C(x_0),\, \dot C(x_n)$ can be known by other methods. (Passed as the tuple `(alpha, beta)` in the code)

References