LAGRANGE_INTERP

Overview

The LAGRANGE_INTERP function computes the Lagrange interpolating polynomial through a given set of data points. The Lagrange polynomial is the unique polynomial of lowest degree that passes exactly through all specified points, making it fundamental in numerical analysis for curve fitting and function approximation.

Given a set of k+1 data points (x_0, y_0), (x_1, y_1), \ldots, (x_k, y_k) with distinct x-coordinates, the Lagrange interpolating polynomial is constructed as a linear combination of Lagrange basis polynomials:

L(x) = \sum_{j=0}^{k} y_j \ell_j(x)

where each basis polynomial \ell_j(x) is defined as:

\ell_j(x) = \prod_{\substack{m=0 \\ m \neq j}}^{k} \frac{x - x_m}{x_j - x_m}

Each basis polynomial equals 1 at its corresponding node x_j and 0 at all other nodes, ensuring the polynomial passes through each data point exactly.

This implementation uses the scipy.interpolate.lagrange function from SciPy, which internally computes the polynomial using Newton’s divided differences formula rather than directly evaluating the Lagrange basis form. The function returns the polynomial coefficients in descending order of powers. For more details on the algorithm, see the SciPy GitHub repository.

Important limitations: The SciPy documentation warns that this implementation is numerically unstable for more than approximately 20 data points. For practical calculations requiring greater numerical stability, the barycentric form of Lagrange interpolation (available via scipy.interpolate.BarycentricInterpolator) is typically more appropriate. Additionally, Lagrange interpolation with equally spaced nodes can exhibit Runge’s phenomenon, where oscillations grow near the boundaries of the interpolation interval.

For theoretical background, see the Wikipedia article on Lagrange polynomials.

This example function is provided as-is without any representation of accuracy.

Excel Usage

=LAGRANGE_INTERP(x, w)
  • x (list[list], required): The x-coordinates of the data points
  • w (list[list], required): The y-coordinates of the data points

Returns (list[list]): A 2D list with one row containing the polynomial coefficients in descending order of powers, or an error message (str) if invalid.

Examples

Example 1: Linear interpolation through two points

Inputs:

x w
0 1
1 2

Excel formula:

=LAGRANGE_INTERP({0;1}, {1;2})

Expected output:

Result
1 1

Example 2: Quadratic polynomial through three points

Inputs:

x w
0 0
1 1
2 4

Excel formula:

=LAGRANGE_INTERP({0;1;2}, {0;1;4})

Expected output:

Result
1 0 0

Example 3: Cubic polynomial through four points (x^3)

Inputs:

x w
1 1
2 8
3 27
4 64

Excel formula:

=LAGRANGE_INTERP({1;2;3;4}, {1;8;27;64})

Expected output:

Result
1 0 0 0

Example 4: Symmetric parabola y = x^2

Inputs:

x w
-1 1
0 0
1 1

Excel formula:

=LAGRANGE_INTERP({-1;0;1}, {1;0;1})

Expected output:

Result
1 0 0

Python Code

from scipy.interpolate import lagrange as scipy_lagrange

def lagrange_interp(x, w):
    """
    Compute the Lagrange interpolating polynomial through a set of points.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.lagrange.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        x (list[list]): The x-coordinates of the data points
        w (list[list]): The y-coordinates of the data points

    Returns:
        list[list]: A 2D list with one row containing the polynomial coefficients in descending order of powers, or an error message (str) if invalid.
    """
    def to2d(val):
        """Convert scalar to 2D list if needed."""
        return [[val]] if not isinstance(val, list) else val

    def flatten(arr):
        """Flatten a 2D list to 1D."""
        return [item for sublist in arr for item in sublist]

    try:
        # Normalize inputs to 2D lists
        x = to2d(x)
        w = to2d(w)

        # Flatten to 1D arrays for scipy
        x_flat = flatten(x)
        w_flat = flatten(w)

        # Validate inputs
        if len(x_flat) != len(w_flat):
            return "Invalid input: x and w must have the same length."

        if len(x_flat) == 0:
            return "Invalid input: x and w must not be empty."

        # Check for duplicate x-coordinates
        if len(x_flat) != len(set(x_flat)):
            return "Invalid input: x-coordinates must be unique."

        # Compute Lagrange polynomial
        poly = scipy_lagrange(x_flat, w_flat)

        # Return coefficients as 2D list (one row), converting numpy types to Python floats
        return [[float(c) for c in poly.coef]]

    except ValueError as e:
        return f"Invalid input: {str(e)}"
    except Exception as e:
        return str(e)

Online Calculator