Jump to content

Multidimensional interpolation: Difference between revisions

From Wikibase
Note that the decimals are written as decimals and kept exact. AI-assisted (RonzzWikiCowriter) (via update-page on MediaWiki MCP Server)
Make the plotting snippet self-contained: it imports numpy, defines the data and basis, and sums the 16 terms for the surface and the query point. AI-assisted (RonzzWikiCowriter) (via update-page on MediaWiki MCP Server)
Line 159: Line 159:
The two coordinates go in as the decimals they are, and `sp.Rational` reads a decimal string exactly, so nothing is rounded: `value` is the exact $\tfrac{3455657}{156250}$, which prints as `22.1162048`, the number the developed form gave above.
The two coordinates go in as the decimals they are, and `sp.Rational` reads a decimal string exactly, so nothing is rounded: `value` is the exact $\tfrac{3455657}{156250}$, which prints as `22.1162048`, the number the developed form gave above.


Plotting the surface needs the same polynomial on a mesh of arguments:
Plotting the surface needs the sum evaluated on a mesh of arguments. This snippet stands on its own:


<syntaxhighlight lang="python" copy>
<syntaxhighlight lang="python" copy>
Line 165: Line 165:
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt


surface_at = sp.lambdify((x1, x2), f)
longitude = np.array([0.0, 1.0, 2.0, 3.0])          # nodes of x1
latitude = np.array([50.0, 51.0, 52.0, 53.0])        # nodes of x2
temperature = np.array([[22.8, 23.6, 24.9, 26.1],
                        [21.7, 22.5, 23.9, 25.0],
                        [20.1, 20.9, 22.3, 23.5],
                        [18.4, 19.1, 20.6, 21.8]])  # row = latitude, column = longitude
 
def basis_at(nodes, x):
    """The Lagrange basis polynomials on `nodes`, evaluated at x."""
    return np.array([np.prod([(x - k) / (i - k) for k in nodes if k != i]) for i in nodes])
 
def f(x1, x2):
    """The 16-term sum: one term per station."""
    return (temperature * np.outer(basis_at(latitude, x2), basis_at(longitude, x1))).sum()


lon_plot = np.linspace(0.0, 3.0, 121)
lon_plot = np.linspace(0.0, 3.0, 121)
lat_plot = np.linspace(50.0, 53.0, 121)
lat_plot = np.linspace(50.0, 53.0, 121)
mesh_lon, mesh_lat = np.meshgrid(lon_plot, lat_plot)
surface = np.array([[f(x, y) for x in lon_plot] for y in lat_plot])
surface = surface_at(mesh_lon, mesh_lat)


fig = plt.figure(figsize=(9.0, 6.8))
fig = plt.figure(figsize=(9.0, 6.8))
ax = fig.add_subplot(111, projection="3d")
ax = fig.add_subplot(111, projection="3d")
ax.set_box_aspect((1.35, 1.0, 0.62))
ax.set_box_aspect((1.35, 1.0, 0.62))
mesh_lon, mesh_lat = np.meshgrid(lon_plot, lat_plot)
surf = ax.plot_surface(mesh_lon, mesh_lat, surface, cmap="RdYlBu_r", linewidth=0,
surf = ax.plot_surface(mesh_lon, mesh_lat, surface, cmap="RdYlBu_r", linewidth=0,
                       antialiased=True, rstride=2, cstride=2, alpha=0.92)
                       antialiased=True, rstride=2, cstride=2, alpha=0.92)
ax.scatter(np.tile(longitude, 4), np.repeat(latitude, 4), np.array(temperature).ravel(),
ax.scatter(np.tile(longitude, 4), np.repeat(latitude, 4), temperature.ravel(),
           s=70, color="#c0392b", edgecolor="black", linewidth=0.9,
           s=70, color="#c0392b", edgecolor="black", linewidth=0.9,
           depthshade=False, label="16 weather stations")
           depthshade=False, label="16 weather stations")
ax.scatter([1.4], [51.6], [float(value)], s=170, color="black", marker="X",
ax.scatter([1.4], [51.6], [f(1.4, 51.6)], s=170, color="black", marker="X",
           depthshade=False, label=r"query point (1.4$^\circ$E, 51.6$^\circ$N)")
           depthshade=False, label=r"query point (1.4$^\circ$E, 51.6$^\circ$N)")
ax.set_xlabel(r"longitude ($^\circ$E)", labelpad=10)
ax.set_xlabel(r"longitude ($^\circ$E)", labelpad=10)

Revision as of 14:36, 27 October 2026

Languages: English · français · Esperanto

Multidimensional interpolation is the process of finding a multivariable function $f(x_1,\cdots,x_m)$ that for a definite set of datapoints $\{(x_{1,i},\cdots,x_{m,i},y_i)\mid i\in [0,n], i \in \mathbb{N}\}$ satisfies $f(x_{1,i},\cdots,x_{m,i})=y_i$.

Methods

Grid interpolation

If a "grid" of $n^m$ datapoints is known, one on each combination of $n$ nodes in each of the $m$ variables:

$$ \{(x_{1,i_1},\cdots,x_{m,i_m},y_{i_1,\cdots,i_m})\mid i_1,\cdots,i_m \in [0,n-1],\, i_1,\cdots,i_m \in \mathbb{N}\} $$

then the interpolant is the multivariable Lagrange polynomial

$$ f(x_1,\cdots,x_m)=\sum_{i_1=0}^{n-1}\cdots\sum_{i_m=0}^{n-1}y_{i_1,\cdots,i_m}\prod_{j=1}^{m}L^{(j)}_{i_j}(x_j),\qquad L^{(j)}_{i}(x_j)=\prod_{\substack{k=0\\k\neq i}}^{n-1}\frac{x_j-x_{j,k}}{x_{j,i}-x_{j,k}} $$

where $L^{(j)}_i$ is the Lagrange basis polynomial of the variable $x_j$, built on that variable's $n$ nodes.

Each factor $L^{(j)}_{i_j}(x_j)$ equals one at the node $x_{j,i_j}$ and zero at the other $n-1$ nodes of $x_j$. The product of the $m$ factors is therefore one at the single datapoint $(x_{1,i_1},\cdots,x_{m,i_m})$ and zero at every other datapoint, so each of the $n^m$ terms carries exactly its own reading and vanishes at all the rest, and the sum passes through all $n^m$ datapoints.

The result is the tensor product interpolant, and it is unique among polynomials of degree at most $n-1$ in each variable: a difference of two of them vanishes at all $n^m$ nodes, and such a difference, read as a polynomial of degree at most $n-1$ in $x_1$, has $n$ roots for every fixed choice of the other variables, so each of its coefficients vanishes at those choices, one variable at a time[1]. In the Lagrange basis the coefficients are the readings themselves, so nothing is solved for: the $n^m$ coefficients and the $n^m$ datapoints are the same numbers.

Pointwise interpolation

Pointwise interpolation (or point evaluation) asks only for the value of $f$ at one new point $(x_1^*,\cdots,x_m^*)$ inside the data range, without constructing $f$ anywhere else. It uses the same grid of $n^m$ datapoints and the same basis polynomials, but regroups the sum one variable at a time instead of writing out its $n^m$ terms.

In two dimensions, the first pass interpolates along $x_1$ inside each row $x_2=x_{2,i_2}$, at the target $x_1^*$:

$$ y^*_{i_2}=\sum_{i_1=0}^{n-1}L^{(1)}_{i_1}(x_1^*)\,y_{i_1,i_2},\qquad \forall i_2\in [0,n-1], i_2 \in \mathbb{N} $$

The $n$ intermediate values $y^*_{i_2}$ sit at the coordinates $(x_1^*,x_{2,i_2})$, i.e., on a one-dimensional grid in $x_2$, so a second pass interpolates them at $x_2^*$:

$$ f(x_1^*,x_2^*)=\sum_{i_2=0}^{n-1}L^{(2)}_{i_2}(x_2^*)\,y^*_{i_2} $$

The first pass costs $n$ one-dimensional interpolations and the second costs $1$. In $m$ dimensions the passes shrink by one variable each time, costing $n^{m-1}, n^{m-2}, \cdots, n^0$:

$$ \sum_{k=0}^{m-1}n^{k}=\frac{n^{m}-1}{n-1} $$

and the passes are exactly the nested form

$$ f(x_1^*,\cdots,x_m^*)=\sum_{i_m=0}^{n-1}L^{(m)}_{i_m}(x_m^*)\sum_{i_{m-1}=0}^{n-1}L^{(m-1)}_{i_{m-1}}(x_{m-1}^*)\cdots\sum_{i_1=0}^{n-1}L^{(1)}_{i_1}(x_1^*)\,y_{i_1,\cdots,i_m} $$

Each of those weighted sums costs $n$ multiplications, so the nested passes cost $n(n^{m}-1)/(n-1)$ in all. That is fewer than the $m\,n^m$ multiplications needed to sum the $n^m$ terms of grid interpolation term by term, because each pass collapses one variable: the first pass does range over the $n^{m-1}$ combinations of known nodes, as a direct sum does, but afterwards one variable is pinned at the target $x_j^*$ and contributes one position instead of $n$. Nothing is thrown away: the same $n^m$ terms are summed either way, and the two counts answer different questions, the value at one point and the whole surface.

The order of the passes does not matter. Collapsing $x_1$ first and then $x_2$ gives the same result as collapsing $x_2$ first and then $x_1$, because the tensor product sum can be regrouped; every ordering evaluates the same polynomial as grid interpolation[2].

Multiplications at one query point, for $n=4$ nodes per axis
$m$ grid interpolation, direct sum, $m\,n^m$ pointwise, nested, $n\sum_{k=0}^{m-1}n^{k}$
2 32 20
3 192 84
4 1024 340

For a general number of variables the passes are most conveniently written as contractions, one per variable:

import numpy as np

temperature = [[22.8, 23.6, 24.9, 26.1],
               [21.7, 22.5, 23.9, 25.0],
               [20.1, 20.9, 22.3, 23.5],
               [18.4, 19.1, 20.6, 21.8]]   # row = latitude, column = longitude

def grid_interpolate_point(nodes, values, point):
    """Interpolated value at `point` from an n_1 x ... x n_m grid.

    nodes  -- one 1-D array of node coordinates per variable, in the same order
              as the axes of `values`
    values -- m-dimensional array, values[i_1, ..., i_m]
    point  -- the m query coordinates
    """
    data = np.asarray(values, dtype=float)
    for axis in range(len(nodes) - 1, -1, -1):       # collapse one variable per pass
        w = [np.prod([(point[axis] - k) / (i - k) for k in nodes[axis] if k != i])
             for i in nodes[axis]]
        data = np.tensordot(data, w, axes=([axis], [0]))
    return float(data)

print(grid_interpolate_point([np.arange(50.0, 54.0), np.arange(0.0, 4.0)],
                             temperature, [51.6, 1.4]))

For the station grid that call returns `22.1162048...`, the same number the example above reaches by summing its 16 terms. It gets there by touching the data in two passes: four longitude interpolations give $24.0936$, $23.0384$, $21.4328$, and $19.6656\ ^\circ$C on the rows at $50$, $51$, $52$, and $53^\circ$N, and one latitude interpolation of those four gives the reading at the query point.

Because these readings happen to be close to planar, bilinear interpolation of the four stations surrounding the query point gives $22.100\ ^\circ$C, only $0.02\ ^\circ$C away from the grid interpolant. The two are not interchangeable, however: the bilinear interpolant is merely continuous where cells meet, whereas the grid interpolant is a single polynomial and therefore smooth everywhere.

References