Feature or enhancement
Proposal:
Add math.lerp(a, b, t) to the math module, computing linear
interpolation between a and b using t as the interpolation
parameter.
This uses the algorithm standardized for C++20's std::lerp (WG21
P0811R3, "Well-behaved interpolation for numbers and pointers" by
S. Davis Herring, [c.math.lerp]), which guarantees properties the
naive a + t * (b - a) formula does not:
lerp(a, b, 0.0) == a exactly
lerp(a, b, 1.0) == b exactly
lerp(a, b, t) is monotonic in t
lerp(a, a, t) == a for any finite t
t outside [0.0, 1.0] is allowed, for extrapolation
Concrete example of why the naive formula isn't good enough:
a = 524560164915884.0
b = -995787893297778.6
a + 1.0 * (b - a) # -995787893297778.5 -- wrong, should equal b exactly
Linear interpolation is a fundamental operation used constantly in
graphics, audio/DSP (crossfades, envelope ramps, resampling),
animation, and numeric code generally. Every major
graphics/systems-adjacent language already has this in its standard
library, using the same numerically careful algorithm: C++20
(std::lerp), .NET (Vector.Lerp and friends). It's also a
recurring ask around Python's own ecosystem (pygame's math module,
various standalone implementations on PyPI/gists), but math itself
has no equivalent.
I searched the tracker and found no prior issue proposing this.
Has this already been discussed elsewhere?
Not that I could find, no existing GitHub issue, and no
discuss.python.org thread specifically about math.lerp.
Links to previous discussion of this feature:
No response
Linked PRs
Feature or enhancement
Proposal:
Add
math.lerp(a, b, t)to themathmodule, computing linearinterpolation between
aandbusingtas the interpolationparameter.
This uses the algorithm standardized for C++20's
std::lerp(WG21P0811R3, "Well-behaved interpolation for numbers and pointers" by
S. Davis Herring, [c.math.lerp]), which guarantees properties the
naive
a + t * (b - a)formula does not:lerp(a, b, 0.0) == aexactlylerp(a, b, 1.0) == bexactlylerp(a, b, t)is monotonic intlerp(a, a, t) == afor any finitettoutside[0.0, 1.0]is allowed, for extrapolationConcrete example of why the naive formula isn't good enough:
Linear interpolation is a fundamental operation used constantly in
graphics, audio/DSP (crossfades, envelope ramps, resampling),
animation, and numeric code generally. Every major
graphics/systems-adjacent language already has this in its standard
library, using the same numerically careful algorithm: C++20
(
std::lerp), .NET (Vector.Lerpand friends). It's also arecurring ask around Python's own ecosystem (pygame's math module,
various standalone implementations on PyPI/gists), but
mathitselfhas no equivalent.
I searched the tracker and found no prior issue proposing this.
Has this already been discussed elsewhere?
Not that I could find, no existing GitHub issue, and no
discuss.python.org thread specifically about
math.lerp.Links to previous discussion of this feature:
No response
Linked PRs