INTERP1D

Overview

The INTERP1D function performs one-dimensional interpolation to estimate values between known data points. Given a set of data points (x_i, y_i) that define a function y = f(x), interpolation constructs a continuous function that passes through all the data points and can be evaluated at any intermediate x value.

This implementation uses the scipy.interpolate.interp1d class from the SciPy library. The function supports multiple interpolation methods via the kind parameter:

  • Linear: Connects data points with straight line segments (default)
  • Nearest/Previous/Next: Returns the nearest, previous, or next data point value
  • Quadratic/Cubic: Uses spline interpolation with polynomial pieces of degree 2 or 3
  • Zero/Slinear: Spline interpolation of zeroth or first order

For spline-based methods, the interpolating curve is constructed from piecewise polynomials with continuous derivatives at the data points. Cubic splines are particularly popular because they produce smooth curves with matching first and second derivatives at each knot, minimizing oscillation while maintaining smoothness.

The fill_value parameter controls behavior for points outside the data range. Setting fill_value='extrapolate' extends the interpolation beyond the original data boundaries, while a numeric value assigns that constant to out-of-bounds queries. The bounds_error parameter can raise an error when extrapolation is attempted.

For more details on 1-D interpolation techniques and alternative approaches, see the SciPy interpolation tutorial. The source code is available on GitHub.

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

Excel Usage

=INTERP1D(x, y, x_new, kind, fill_value, bounds_error)
  • x (list[list], required): X-coordinates of data points (must be in ascending order)
  • y (list[list], required): Y-coordinates of data points (same length as x)
  • x_new (list[list], required): X-coordinates where interpolated values are needed
  • kind (str, optional, default: “linear”): Interpolation method to use
  • fill_value (str, optional, default: “extrapolate”): Value for points outside data range (use ‘extrapolate’ or a number)
  • bounds_error (bool, optional, default: false): Whether to raise error for out-of-bounds points

Returns (list[list]): A 2D list of interpolated y-values, or error message string.

Examples

Example 1: Demo case 1

Inputs:

x y x_new
0 0 0.5
1 1 1.5
2 4 2.5
3 9

Excel formula:

=INTERP1D({0;1;2;3}, {0;1;4;9}, {0.5;1.5;2.5})

Expected output:

Result
0.5
2.5
6.5

Example 2: Demo case 2

Inputs:

x y x_new kind
0 0 1.5 cubic
1 1 2.5
2 8
3 27
4 64

Excel formula:

=INTERP1D({0;1;2;3;4}, {0;1;8;27;64}, {1.5;2.5}, "cubic")

Expected output:

Result
3.375
15.625

Example 3: Demo case 3

Inputs:

x y x_new kind fill_value
1 2 0.5 linear extrapolate
2 4 3.5
3 6

Excel formula:

=INTERP1D({1;2;3}, {2;4;6}, {0.5;3.5}, "linear", "extrapolate")

Expected output:

Result
1
7

Example 4: Demo case 4

Inputs:

x y x_new kind fill_value bounds_error
0 1 0.5 linear extrapolate false
1 2 1.5
2 3 2.5
3 4

Excel formula:

=INTERP1D({0;1;2;3}, {1;2;3;4}, {0.5;1.5;2.5}, "linear", "extrapolate", FALSE)

Expected output:

Result
1.5
2.5
3.5

Python Code

from scipy.interpolate import interp1d as scipy_interp1d
import numpy as np

def interp1d(x, y, x_new, kind='linear', fill_value='extrapolate', bounds_error=False):
    """
    Interpolate a 1-D function.

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

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

    Args:
        x (list[list]): X-coordinates of data points (must be in ascending order)
        y (list[list]): Y-coordinates of data points (same length as x)
        x_new (list[list]): X-coordinates where interpolated values are needed
        kind (str, optional): Interpolation method to use Valid options: Linear, Nearest, Zero, Slinear, Quadratic, Cubic, Previous, Next. Default is 'linear'.
        fill_value (str, optional): Value for points outside data range (use 'extrapolate' or a number) Default is 'extrapolate'.
        bounds_error (bool, optional): Whether to raise error for out-of-bounds points Default is False.

    Returns:
        list[list]: A 2D list of interpolated y-values, or error message string.
    """
    def to2d(val):
        return [[val]] if not isinstance(val, list) else val

    def flatten(arr):
        return [item for sublist in arr for item in sublist]

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

        # Flatten 2D lists to 1D
        x_list = flatten(x)
        y_list = flatten(y)
        x_new_list = flatten(x_new)

        # Validate numeric types before numpy conversion
        for val in x_list + y_list + x_new_list:
            if not isinstance(val, (int, float, bool)):
                return "Error: Input arrays must contain only numeric values."

        # Convert to numpy arrays
        x_flat = np.array(x_list)
        y_flat = np.array(y_list)
        x_new_flat = np.array(x_new_list)

        # Validate input dimensions
        if x_flat.ndim != 1 or y_flat.ndim != 1:
            return "Error: Input arrays x and y must be 1-dimensional."

        if x_flat.shape[0] != y_flat.shape[0]:
            return "Error: Input arrays x and y must have the same length."

        if len(x_flat) == 0 or len(y_flat) == 0:
            return "Error: Input arrays x and y must contain at least one data point."

        # Check minimum data points for interpolation method
        min_points_required = {
            'linear': 2, 'nearest': 1, 'zero': 1, 'slinear': 2,
            'quadratic': 3, 'cubic': 4, 'previous': 1, 'next': 1
        }
        min_points = min_points_required.get(kind, 2)
        if len(x_flat) < min_points:
            return f"Error: Interpolation method '{kind}' requires at least {min_points} data points."

        # Validate x values are in ascending order
        if not np.all(x_flat[:-1] < x_flat[1:]):
            return "Error: X-coordinates must be in strictly ascending order."

        # Create interpolation function
        interp_func = scipy_interp1d(
            x_flat,
            y_flat,
            kind=kind,
            fill_value=fill_value,
            bounds_error=bounds_error
        )

        # Evaluate interpolation at new points
        y_new = interp_func(x_new_flat)

        # Return as 2D list (column vector), converting numpy types to Python floats
        return [[float(val)] for val in y_new]

    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator