C++ Basics: Interpolate a Reading with std::lerp
Use a fractional position to interpolate between two readings and recognize extrapolation.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as lerp-interpolation-extrapolation-demo.cpp:
#include <cmath>
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::fixed << std::setprecision(2);
for (double position : {0.0, 0.25, 1.0, 1.5}) {
std::cout << position << ": " << std::lerp(10.0, 30.0, position) << '\n';
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic lerp-interpolation-extrapolation-demo.cpp -o lerp-interpolation-extrapolation-demo &&
./lerp-interpolation-extrapolation-demoObserved output:
0.00: 10.00
0.25: 15.00
1.00: 30.00
1.50: 40.00Read the result
Positions 0 and 1 select the two endpoints. Position 0.25 gives 15, one quarter of the way from 10 to 30. Position 1.5 gives 40 because the function continues beyond the second endpoint. The display uses two decimal places; it does not change the stored values.
Apply it carefully
The interpolation parameter is not a percentage integer: 25 percent is 0.25. std::lerp does not clamp it to the interval from 0 to 1. Validate or bound it separately when extrapolation is forbidden. This example uses finite values with exactly representable results; general floating-point calculations can still round. Define an application policy for nonfinite inputs before interpolating sensor data.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- lerp-interpolation-extrapolation-demo.cpp lerp-interpolation-extrapolation-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.