Date: Sun, 13 Apr 2025 17:23:03 +0200
Hi.
`std::lerp` is useful to get an interpolation between a and b, that is get a value interpolated or extrapolated. But curiously the inverse lerp function is missing from the standard.
The inverse interpolation lets you find out how far along a value is between a and be. For example
lerp_inv(100.0, 200.0, 180.0) == 0.8
lerp_inv(100.0, 200.0, 0.0) == -1.0
lerp_inv(100.0, 200.0, 300.0) == 2.0
for lerp_inv(a, b, x) it should hold true
lerp(a, b, lerp_inv(a, b, x)) == x
The naive implementation is
```cpp
template <typename T>
requires std::is_arithmetic_v<T> // can we also get
concept std::arithmetic, please?
constexpr T lerp_inv(const T a, const T b, const T x) noexcept {
return (x - a) / (b - a);
}
```
Though as with lerp and midpoint, there are a whole lot of caveats to make it break for edge cases, for example integer overflow, division by zero (lerp_inv(42, 42, 42)), or floating point precision issues.
A correct and performant standard implementation of lerp_inv would be useful as this function is used in many domains and is hard to do correctly in the general case.
Use cases are, for example:
- Mathematics: Normalize a value in a known range. Example:
Convert x in [a, b] to [0, 1]
- Games: Calculate animation progress, blend weights, or
procedural transitions. Example: A character starts moving at
100ms and finishes at 200ms. lerp_inv(100, 200, current_time)
gives normalized animation progress.
- Graphics and Shader Programming: Color gradient mapping, texture
blending, coordinate normalization. Example: Mapping a height
value to a color: float t = lerp_inv(min_height, max_height,
current_height); then use lerp(colorA, colorB, t).
- Data Visualization / UI Design: Mapping sensor input or data
values to screen coordinates. Example: Map temperature range [15,
40] to pixel Y-coordinates [100, 300]
- Machine Learning / DSP: Normalize feature inputs, remap ranges,
detect position within sliding windows.
- Control Systems / Automation: Scale sensor inputs (voltage,
temperature, etc.) to control outputs.
- Finance: Normalize input parameters for risk models or scoring
systems.
and many more.
As you can see, inverse lerp is used across basically all
domains, and is non trivial to do correctly. As such an inclusion
in the standard would be beneficial.
Received on 2025-04-13 15:23:07