Skip to main content

Pchips

sin(x) from 11 samples: SciPy cuts the peak off flat, Pchips follows it

Overview

This is a Python port, produced using Gemini CLI in an afternoon, of the accurate monotone cubic interpolant originally implemented in MATLAB here. It was then refined using Claude Code: checked against Huynh's paper (which turned up and fixed two bugs in the M4 constraint inherited from the MATLAB original), turned into a drop-in replacement for SciPy's PchipInterpolator, vectorized, and given a more thorough test suite.

All the logic is in interpolate.py. The tests compare it to SciPy, check the guarantees from Huynh's paper and generate comparison plots. test_scipy_suite.py runs SciPy's own PchipInterpolator tests against it.

The algorithm, due to H. T. Huynh, is described in this NASA Technical Memo, which is self-contained and quite readable. A nearly identical version was later published in the SIAM Journal on Numerical Analysis.

These plots show where Pchips differs from SciPy's PchipInterpolator, and how its options differ from each other. They are generated by make_gallery.py: run uv run python scripts/make_gallery.py to regenerate them.

Preserving versus imposing monotonicity

Peaks and troughs

In the plot at the top of this page, the peak of sin(x) falls exactly between two samples with equal values, so the data are flat there. SciPy's interpolant imposes monotonicity by setting the derivative to zero at both samples, which cuts the peak off flat at 0.951. Pchips only preserves monotonicity where the data are monotone, so it follows the curve up to 1.002, close to the true peak of 1. The maximum error is 0.049 for SciPy and 0.0055 for Pchips.

Accuracy as the samples get denser

Maximum error for sin(x) vs number of samples

Flattening every peak and trough limits SciPy's interpolant to O(h²) accuracy, while Pchips is O(h⁴): doubling the number of samples cuts SciPy's error by a factor of 4, and Pchips' by 16. With 641 samples, the maximum error is 3.6e-6 for SciPy and 3.6e-10 for Pchips.

Monotone data stay monotone

Akima's data with a cubic spline, SciPy and Pchips

On monotone data, both PCHIPs give a monotone interpolant with no overshoot, unlike a cubic spline, which dips to 4.74 on data which never go below 10 and bulges above 60 between the samples at 50 and 60.

The price: overshoot on rough data

20 random values, SciPy vs Pchips

Relaxing the constraint near peaks and troughs means Pchips can overshoot the data there. On smooth data the overshoot is small and usually closer to the truth, as in the plot at the top. On rough data it can be large: on these 20 random values in [0.08, 0.93], from SciPy's own test_overshoot, Pchips reaches 1.43, while SciPy stays within the range of the data.

Cubic versus quartic

Maximum error for exp(-x²) vs number of samples, SciPy and both approximations

Both derivative approximations give an O(h⁴) interpolant, but the quartic one has a smaller error constant: with 641 samples of e^(−x²), the maximum error is 3.6e-9 with cubic and 2.5e-10 with quartic (and 6.5e-6 with SciPy). With very few samples, however, quartic can be worse, since it relies on the data being smooth over five neighbouring samples rather than four: with 11 samples, the error is 3.6e-2 with cubic and 5.2e-2 with quartic. Use quartic once the samples resolve the shape of the data.

M3 versus M4

M3 vs M4: error for x - sin(x), and monotone data

Left: on smooth, well-sampled data, M3 and M4 give the same interpolant except near a flat inflection point, where the slope of a monotone function drops to zero between samples, as for x - sin(x) at x = 0. There, M3 clips the derivatives to keep the interpolant monotone and loses accuracy: with 41 samples, the maximum error is 1.8e-5 with M3 and 6.7e-6 with M4.

Right: the price of M4. To stay fourth-order accurate, M4 allows derivatives which can make the interpolant non-monotone on rough monotone data. On this data set, which increases at every sample, the M4 interpolant decreases by 0.11 between x = 3.5 and x = 4.5, while the M3 interpolant stays monotone.

Classic data sets

These are the data sets in data, which the tests also use. Each plot compares SciPy with Pchips' default settings (and, for Akima's data, the quartic approximation too).

Hyman

Hyman data, SciPy vs Pchips

Nine samples of e^(−x²), with the peak between the samples at ±0.4. SciPy cuts the peak off flat at 0.852, an error of 0.148, while Pchips reaches 0.988, an error of 0.012. Away from the peak, nine samples are too few for either interpolant to follow the curve closely, and Pchips is off by up to 0.128 at x = 1.06.

Moler

Moler data, SciPy vs Pchips

Rough, non-monotone data with plateaus and sharp turns. SciPy stays within the data, flat across the plateau at 1.2. Pchips treats the two samples at 1.2 as either side of a peak and rounds it off up to 1.57, then dips to -0.118 between the samples at 0.1 and 0. This is the overshoot described in Reasons not to switch: if the plateau and the zero floor are real features of the data, SciPy is the better choice here.

Akima

Akima data, SciPy vs Pchips cubic and quartic

Monotone data with a sharp rise, one of the test cases in Huynh's paper. All three interpolants are monotone and stay within the data. SciPy and Pchips' default differ by at most 1.8, on the final rise from 60 to 85. The quartic approximation, which draws on more neighbouring samples, stands out between the samples at 50 and 60: it levels off close to 60 (59.4 at x = 13.5, against 57.0 and 56.8), then rises more steeply to 85. (See above for a cubic spline on the same data.)

RPN 14

RPN 14 data, SciPy vs Pchips

Monotone data which rise steeply and then level off, from Fritsch and Carlson's paper on monotone interpolation, and the other test case in Huynh's paper. SciPy and Pchips are both monotone and differ by at most 0.036, mostly near the bottom of the rise.

Titanium

Titanium data, SciPy vs Pchips

A sharp peak which happens to fall on a sample, so neither interpolant overshoots it, and both stay within the data. They differ by at most 0.12, at the foot of the peak. Pchips is flat for a moment at the sample at x = 855: its derivative estimate there came out with the wrong sign for the rising data, so the monotonicity constraint set it to zero.

Installation

Pchips requires Python 3.10 or later, NumPy 1.23.5 or later and SciPy 1.10 or later. It is not on PyPI, so install it from GitHub:

pip install git+https://github.com/vglazer/pchips
# or
uv add git+https://github.com/vglazer/pchips

Usage

Change the import and leave everything else as it is:

# from scipy.interpolate import PchipInterpolator, pchip_interpolate
from pchips import PchipInterpolator, pchip_interpolate

interp = PchipInterpolator(x, y)            # also axis=..., extrapolate=...
interp(u)                                   # also interp(u, nu=1)
interp.derivative(), interp.antiderivative(), interp.integrate(a, b), interp.roots()

PchipInterpolator has the same signature and input validation as SciPy's, and like SciPy's version it is a CubicHermiteSpline, so it has the same methods, output shapes and extrapolation behavior. On top of that, two keyword-only options select the variant of Huynh's method:

  • approx_order: 'cubic' (default) or 'quartic', the derivative approximation
  • mono_constraint: 'M3' (default) or 'M4', the monotonicity constraint

See below for when to use which. With fewer than five data points, the result is the same as SciPy's, up to rounding error.

As with SciPy, extrapolation is on by default and simply extends the first and last cubics, so the interpolant drifts away from the data quickly outside its range. Pass extrapolate=False to get nan there instead.

Choosing between cubic and quartic

Use 'quartic' if your data are smooth and sampled finely enough to resolve their features, and 'cubic', the default, otherwise.

Why:

  • Quartic is more accurate on well-resolved smooth data. Both give an O(h⁴) interpolant, but the quartic derivative approximation has a smaller error constant. With 321 samples, the maximum error is 3.9e-10 instead of 5.8e-9 for sin(x), and 4.2e-9 instead of 5.8e-8 for e^(−x²)
  • Cubic can be more accurate on coarse data. The quartic approximation uses five neighbouring samples instead of four, so it relies on the data being smooth over a wider stencil. With only 11 samples of e^(−x²) on [-3, 3], the maximum error is 5.2e-2 with quartic and 3.6e-2 with cubic, and the same happens with a steep tanh(5x) and Runge's function
  • Quartic is about 10% slower to construct

Choosing between M3 and M4

Use M3, the default, unless your data are smooth samples of a monotone function whose slope drops to zero somewhere between the samples, i.e. a flat inflection point such as x - sin(x) at x = 0 or x³ at x = 0.

Why:

  • On most data the two are identical. For smooth, well-sampled data the constraint only kicks in near points where the slope of the data is close to zero. At peaks and troughs both constraints relax in the same way, which is what gives Pchips its accuracy there. On sin, e^(−x²), tanh, Runge's function and others, M3 and M4 give exactly the same interpolant
  • M4 is more accurate at flat inflection points. M3 guarantees monotonicity by keeping the derivative at each sample between 0 and a bound computed from the neighbouring data: 3 times the smaller of the neighbouring slopes, or 1.5 times a local parabola's slope if that is larger. Near a flat inflection point, both are tiny, so this clips the derivatives and accuracy drops to roughly O(h³), and erratically so. M4 uses extra information from neighbouring cubics to allow larger derivatives there and stays O(h⁴). For x - sin(x) on [-2, 3.1] with 641 samples, the maximum error is 7.1e-10 with M3 and 1.0e-10 with M4 (see test_m4_fourth_order_at_flat_inflection in test_vs_scipy.py). For x³, M4 is exact while M3 is not. If the flat point happens to be one of the samples, the two agree again
  • M4 weakens the monotonicity guarantee. Fourth-order accuracy is incompatible with monotonicity in general: there are monotone data which lie on a non-monotone cubic, and M4 reproduces the cubic. Huynh therefore only guarantees a monotone interpolant where the data are "q-monotone" (Theorem 3 in the paper), and in the two intervals at either end. On rough monotone data this matters: in 300 random monotone datasets, M4 gave an interpolant which decreases somewhere in 82 (equally spaced samples) and 141 (unequally spaced samples) of them, while M3 never did
  • M4 is about 1.4-1.6 times slower to construct

So if your data are noisy or irregular, or a monotone result is a hard requirement, stick with M3. If they are smooth and you need the extra accuracy near flat inflection points, use M4, and check the result for monotonicity if that matters.

Should you switch from SciPy?

In short: switch if your data come from a smooth underlying function and accuracy matters, especially near peaks and troughs. Stay with SciPy if your code relies on the interpolant never leaving the range of the data.

Reasons to switch

  • Much higher accuracy near local extrema. SciPy's interpolant flattens out at every local maximum and minimum, which makes it only O(h²) accurate there. Pchips is O(h⁴) there too, and everywhere else, except at flat inflection points with the default M3 constraint (see above). Here is the maximum error with 321 equally spaced samples (see test_convergence_vs_scipy in test_vs_scipy.py):

    Function SciPy Pchips (default) Pchips (approx_order='quartic')
    sin(x) on [0, 2π] 1.4e-5 5.8e-9 3.9e-10
    e^(−x²) on [-3, 3] 2.6e-5 5.8e-8 4.2e-9
    tanh(x) on [-3, 3] (no extrema) 2.1e-7 1.3e-8 1.4e-9

    Put differently, Pchips with 41 samples of sin(x) (2.2e-5) is nearly as accurate as SciPy with 321 (1.4e-5), and the gap grows as you add samples

  • The same monotonicity guarantee. With the default M3 constraint, monotone data give a monotone interpolant, just like SciPy's

  • Low-degree polynomials are reproduced exactly, along with their derivatives and integrals. Quadratics always are, and so are cubics with M4. With the default M3, cubics are exact where they are monotone, but not across a flat inflection point, nor near their extrema when the samples are coarse. SciPy's interpolant is not exact even for quadratics

  • Switching is a one-line change. Only the import changes, and SciPy's own PchipInterpolator tests pass, apart from two: one checks that the interpolant never overshoots, which Huynh's method deliberately gives up, and the other checks the exact values of SciPy's method (see test_scipy_suite.py)

Reasons not to switch

  • The interpolant may overshoot the data near strict local extrema. This is the price of accuracy: between any two neighbouring samples, SciPy's interpolant always stays between their values, which is exactly what limits it to O(h²) at peaks and troughs. How far Pchips overshoots depends on how smooth the data are:

    • On smooth data the overshoot is small, and usually closer to the truth, since the underlying function typically peaks between samples. For example, data with a minimum of 0.02 can give an interpolant which dips to -0.004
    • On rough data it can be large. In SciPy's test_overshoot, which interpolates 20 random values (one of the two expected failures in test_scipy_suite.py), Pchips leaves the range of the neighbouring samples in 3 of the 19 intervals, by up to 0.50 when the data span 0.86

    If that matters, e.g. for probabilities, concentrations or anything passed to log, stay with SciPy or clip the result

  • Construction is 1.3-3 times slower (see below). This only matters if you build interpolators in a hot loop

  • Rough or noisy data gain little, since the higher accuracy relies on the data being smooth

Performance

Evaluating the interpolant, along with its derivatives and integrals, is exactly as fast as SciPy's, since both use the same CubicHermiteSpline code: about 0.5 ms for 100,000 points. Construction does more work, because Huynh's method uses higher-order divided differences and a more elaborate monotonicity constraint. Construction times, best of 7 runs on an Apple M3 Max with Python 3.13, NumPy 2.3 and SciPy 1.16, with the slowdown relative to SciPy in brackets:

Data SciPy Pchips (default) Pchips (approx_order='quartic', mono_constraint='M4')
20 points 0.05 ms 0.08 ms (1.6× slower) 0.11 ms (2.2× slower)
1,000 points 0.06 ms 0.10 ms (1.6× slower) 0.14 ms (2.3× slower)
100,000 points 1.3 ms 2.3 ms (1.8× slower) 3.7 ms (2.9× slower)
50 points × 1,000 columns 0.9 ms 1.1 ms (1.3× slower) 1.7 ms (1.9× slower)

Mathematical background

The mathematical background is written in LaTeX, which PyPI cannot display, so read it on GitHub.

Development

  • Make sure you have uv installed
  • Clone the repo
  • cd pchips
  • uv sync
  • uv run pytest
  • Check out the comparison plots in the plots subdirectory

Citation

If you use Pchips in published work, please cite Huynh's paper:

@article{huynh1993accurate,
  author  = {Huynh, Hung T.},
  title   = {Accurate Monotone Cubic Interpolation},
  journal = {SIAM Journal on Numerical Analysis},
  volume  = {30},
  number  = {1},
  pages   = {57--100},
  year    = {1993},
  doi     = {10.1137/0730004}
}

License

Pchips is released under the MIT License. test_scipy_suite.py is adapted from SciPy's tests and keeps SciPy's BSD 3-Clause License, which is reproduced at the top of that file.

Metadata

Release files for pchips 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pchips 1.0.0
File Size Uploaded Provenance Actions
pchips-1.0.0.tar.gz 27.3 kB Without provenance Details for pchips-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pchips 1.0.0
File Interpreter ABI Platform Actions
pchips-1.0.0-py3-none-any.whl Python 3 none any Details for pchips-1.0.0-py3-none-any.whl

Total release size: 39.1 kB

Release files / pchips-1.0.0.tar.gz

Download URL pchips-1.0.0.tar.gz
Size 27.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b4f73a6dbecb1dea84c3fcffad0e20b2b45a0b4712352227724289cbd2c04a6c
BLAKE2b-256 checksum
How to use checksums
937c0f85edd3a583b063cf4561f2614cb34af7d4334f3a087b2039fdc0690969
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.21

Release files / pchips-1.0.0-py3-none-any.whl

Download URL pchips-1.0.0-py3-none-any.whl
Size 11.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8471bc8ed54c9bf542fad8ac8f0306f2c26e43e80e07c5e410d585bf572419ef
BLAKE2b-256 checksum
How to use checksums
b5b749571f694c14c6dfa61f265036cd1417ec1d9cbb892eb4771df968e428f1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.21

Security for pchips 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page