Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Interpolation and Smoothing

One-Dimensional Interpolation

Learn 1D interpolation in SciPy: np.interp, CubicSpline, PchipInterpolator and Akima, boundary conditions, why extrapolation fails, and the Runge phenomenon.

You measured a temperature at 9:00, 10:00 and 11:00, and now someone asks for 10:20. Interpolation builds a function that passes exactly through your data points so that you can evaluate it anywhere in between. It is used to resample uneven data onto a regular grid, to draw smooth curves through a few samples, to evaluate a tabulated function (such as a lookup table of a sensor's calibration), and to make derivatives and integrals of sampled data available.

The catch is that infinitely many curves pass through the same points. A good interpolant is one whose shape between the points is sensible for your data: no invented wiggles, no overshoot, no wild behaviour at the edges. This lesson compares the main choices in scipy.interpolate and shows what can go wrong.

A note on names. Older tutorials use scipy.interpolate.interp1d, which still exists but is considered legacy and receives no new features. The patterns below are its recommended replacements.

Old interp1d call Use instead
kind="linear" np.interp(x_new, x, y)
kind="cubic" CubicSpline(x, y)
kind="quadratic", other orders make_interp_spline(x, y, k=...)
monotone data PchipInterpolator(x, y)

All of the spline classes are callable: build the object once from the data, then call it with new x values, scalars or arrays.

flowchart LR
    D["data points<br/>x (increasing), y"] --> B["build interpolant<br/>CubicSpline(x, y)"]
    B --> O["callable object f"]
    Q["new x values"] --> O
    O --> R["interpolated y values"]

Build once from the data, then evaluate as often as you like.

Four interpolants on the same data

Different methods trade smoothness against faithfulness. Linear interpolation joins points with straight lines: it never overshoots but has corners. A cubic spline fits a piece of cubic polynomial between neighbouring points and makes the curve smooth (continuous first and second derivatives). PCHIP (piecewise cubic Hermite) and Akima also give smooth curves but pick the slopes locally, which keeps them from overshooting.

Python Linear, cubic, PCHIP and Akima

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All four curves hit the black dots exactly; they differ between the dots. Compare the curves between x = 1 and x = 4, where they differ most: the cubic spline swings further than PCHIP, which hugs the data.

The low-level spline interface: splrep and splev

Before the class-based spline objects existed, SciPy offered two functions that you will meet in older code and in tutorials. They are still supported.

  • tck = interpolate.splrep(x, y, k=3, s=0) fits a B-spline to the data and returns a tuple tck = (knots t, coefficients c, degree k). With s=0 the curve passes through every point (interpolation). With s > 0 it becomes a smoothing spline that stays within a total squared error of about s, which is how you smooth noisy data.
  • interpolate.splev(x_new, tck, der=0) evaluates the spline (or, with der=1, 2, ..., its derivatives) at new positions.
  • interpolate.splint(a, b, tck) integrates the spline between two points, and interpolate.sproot(tck) finds its zeros.

The modern equivalents are make_interp_spline, make_smoothing_spline and BSpline objects, which carry the same knots and coefficients as BSpline(*tck). The old pair needs the x values to be strictly increasing.

Python splrep, splev, splint and a smoothing spline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With s=0 the spline reproduces the points exactly and wiggles through the noise; with s near n * sigma**2 (sample count times the noise variance) it follows the sine wave. Pick s from what you know about the noise, not by trial alone. For new code, make_smoothing_spline(x, y, lam=...) offers the same idea with a penalty parameter, and UnivariateSpline wraps splrep in a class (the class-based interpolants appear throughout this lesson).

Overshoot: when smooth is too smooth

A standard cubic spline minimises curvature over the whole data set, so a change at one end can ripple through the entire curve. For data with a sudden step the spline rings on both sides of the jump and goes outside the range of the data. That is a serious problem if the quantity cannot physically go there (a concentration below zero, a percentage above 100).

PCHIP is built to preserve monotonicity: wherever the data increases, the curve increases, and it never leaves the range of the neighbouring points. Akima is similar and tends to look natural for curves with sharp bends.

Python A step through the data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The spline dips below 0 and rises above 1 by about 0.1, while PCHIP and Akima stay inside the data range. As a rule of thumb: use CubicSpline for smooth physical curves where you want continuous second derivatives, and PchipInterpolator when staying inside the data (or keeping monotonicity) matters more than smoothness.

Boundary conditions for splines

A cubic spline through n points leaves two degrees of freedom undetermined; the bc_type argument fills them in:

  • "not-a-knot" (the default): works well when you know nothing about the ends.
  • "natural": the second derivative is zero at both ends, as if the curve straightens out.
  • "clamped": the first derivative is zero at both ends; use it for a curve that must flatten.
  • "periodic": the curve joins up smoothly; the first and last y values must be equal.
  • A tuple like ((1, 0.0), (2, 0.0)) gives the derivative order and value at each end for full control.

Because a spline object stores polynomials, it can also differentiate, integrate and find roots exactly (with respect to the interpolant): cs(x, 1) is the first derivative, cs.derivative() returns a new spline, and cs.integrate(a, b) integrates.

Python Boundary conditions and derivatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For a function like sin, the periodic and natural conditions win by a wide margin, because they match what the function really does: it repeats, and its second derivative is zero at both ends. The clamped condition is the worst here, because forcing a zero slope at x = 0 is simply wrong for a sine curve. The lesson: pick the boundary condition that matches what you know about the data, not just the default.

Extrapolation dangers

Interpolation answers questions inside the range of your data. Asking for a value outside is extrapolation, and it is a different, much riskier game. CubicSpline extrapolates by default by extending the last cubic piece, and a cubic grows like x**3 very quickly. np.interp takes the opposite approach and silently returns the end value, which looks reasonable but is also invented.

Python Going beyond the data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Right at the edge the spline is fine, half a unit past it is already off, and two units past it the value is more than double the true value. At 4*pi the spline reports about -9 for a function that never leaves [-1, 1]. np.interp flatlines at the last value, which is wrong in a quieter way.

Warning: Do not trust an interpolant outside the data range. If you must extrapolate, use a model that reflects the physics (a fitted line, an exponential, see Curve Fitting and Least Squares) and treat the result as a forecast, not a measurement. Passing extrapolate=False turns accidental extrapolation into visible nan values.

The Runge phenomenon

A tempting idea: more points, more accuracy, so fit one high-degree polynomial through all of them. For evenly spaced points, this backfires. Runge's classic example is 1 / (1 + 25 x**2) on [-1, 1]: as the degree rises, the polynomial matches better in the middle but oscillates more and more violently near the ends, and the maximum error grows.

Piecewise methods avoid this, because each piece only uses nearby points. If you really need a single polynomial, place points more densely near the ends (Chebyshev points) instead of evenly.

Python High-degree polynomials versus splines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The polynomial error grows from about 0.4 to over 14 as points are added, while the spline error shrinks steadily. The practical takeaway: for tabulated data, use splines (or PCHIP), not one big polynomial.

Choosing an interpolant

  • Need speed, no surprises, corners are fine: np.interp.
  • Smooth curve through accurate (low-noise) data: CubicSpline, with a boundary condition that fits what you know.
  • Data must stay inside its range or stay monotonic (cumulative totals, probabilities): PchipInterpolator.
  • Data with sharp bends and no desire for overshoot: Akima1DInterpolator.
  • Noisy data: do not interpolate at all. An interpolant passes exactly through every noisy point, so the noise becomes part of the curve. Use smoothing instead; the next lesson covers smoothing splines in Multidimensional and Scattered-Data Interpolation, and Curve Fitting and Least Squares shows model fitting.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the recommended replacement for interp1d(x, y, kind='linear')?

    np.interp does piecewise linear interpolation directly. The other options either use a different curve or fit a model instead of passing through the points.
  2. 2. Your data is a step from 0 to 1 and must never leave the range [0, 1]. Which interpolant fits best?

    PCHIP preserves monotonicity and does not overshoot. A cubic spline rings around the step and leaves the range, and a high-degree polynomial is worse.
  3. 3. What does CubicSpline(x, y, bc_type='periodic') require?

    A periodic spline joins its two ends smoothly, so the first and last y values must be equal.
  4. 4. A spline fitted on x in [0, 10] is evaluated at x = 30 and gives an absurd result. What happened?

    Cubic pieces grow fast outside the data range. Interpolants are only trustworthy inside it; use extrapolate=False to get nan instead of a misleading number.
  5. 5. Why does a single high-degree polynomial through evenly spaced points often do worse as you add points?

    With equally spaced nodes the interpolating polynomial can oscillate wildly near the interval ends, and the maximum error increases with degree. Piecewise splines avoid this.

Summary

  • An interpolant passes exactly through the data; build it once (CubicSpline(x, y)) and call it with new x values. x must be strictly increasing.
  • Replace the legacy interp1d with np.interp (linear), CubicSpline or make_interp_spline (smooth) and PchipInterpolator (monotone, no overshoot).
  • CubicSpline can overshoot near steps; PCHIP and Akima stay closer to the data.
  • Choose the bc_type that matches what you know: "periodic" for cycles, "clamped" or "natural" for known end behaviour.
  • Never trust an interpolant outside the data range; extrapolate=False makes the problem visible.
  • Avoid one high-degree polynomial through evenly spaced points (Runge phenomenon); do not interpolate noisy data.

Next up: surfaces and scattered points in Multidimensional and Scattered-Data Interpolation.