Skip to content

gh-154573: Add math.lerp() for linear interpolation#154574

Open
PhysicistJohn wants to merge 2 commits into
python:mainfrom
PhysicistJohn:gh-154573-math-lerp
Open

gh-154573: Add math.lerp() for linear interpolation#154574
PhysicistJohn wants to merge 2 commits into
python:mainfrom
PhysicistJohn:gh-154573-math-lerp

Conversation

@PhysicistJohn

Copy link
Copy Markdown

Adds math.lerp(a, b, t), computing linear interpolation between a
and b using the algorithm standardized for C++20's std::lerp
([c.math.lerp], WG21 P0811R3 "Well-behaved interpolation for numbers
and pointers" by S. Davis Herring). Fixes gh-154573.

Unlike the naive a + t * (b - a) formula, this guarantees:

  • exact endpoints (lerp(a, b, 0.0) == a, lerp(a, b, 1.0) == b)
  • monotonicity in t
  • lerp(a, a, t) == a for any finite t

I verified this port against the real algorithm several independent
ways before opening this:

  • Compiled a C++20 program against libc++'s actual std::lerp and
    diffed bit patterns across ~25 test vectors, including inf/NaN edge
    cases: bit-for-bit identical.
  • Compared directly against LLVM's shipping libcxx/include/cmath
    source: the algorithm is line-for-line the same, modulo variable
    names.
  • Property-tested 200,000 random (a, b, t) triples for endpoint
    exactness, monotonicity, and the a == b invariant: zero failures.
  • Full test_math.py / test_cmath / test_capi regression run: no
    failures, no new compiler warnings.
  • Built the full Sphinx docs with warnings-as-errors: no new warnings.

Includes tests (LerpTests in test_math.py), docs
(Doc/library/math.rst), a What's New entry, and a NEWS entry.

Adds math.lerp(a, b, t), computing linear interpolation between a
and b using the algorithm standardized for C++20's std::lerp
([c.math.lerp], WG21 P0811R3 "Well-behaved interpolation for numbers
and pointers" by S. Davis Herring).

Unlike the naive "a + t * (b - a)" formula, this guarantees exact
endpoints (lerp(a, b, 0.0) == a, lerp(a, b, 1.0) == b), monotonicity
in t, and lerp(a, a, t) == a for any finite t.

Includes tests (LerpTests in test_math.py), docs, a What's New entry,
and a NEWS entry.
@read-the-docs-community

read-the-docs-community Bot commented Jul 24, 2026

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #33737023 | 📁 Comparing 4cd8493 against main (66e313f)

  🔍 Preview build  

3 files changed
± library/math.html
± whatsnew/3.16.html
± whatsnew/changelog.html

Missed this in the initial commit -- the detailed function docs were
there but the table at the top of the page (which lists fma, fmax,
fmin, etc.) didn't have an entry.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add math.lerp() for linear interpolation

1 participant