Mid-point and linear interpolation done right


How many times did we write code like:

auto middle = (start+stop) / 2
auto interpolate = start + ((stop-start)*numerator) / denominator

Although this code is correct, it may suffer from overflows. The typical way to avoid those is to cast to a wider type. But how can you do this when the start and stop values are already using the largest integer type (eg. int64_t) ?

The C++ standard library has you covered now with:

auto middle = std::midpoint(start, stop);
auto interpolate = std::lerp(start, stop, static_cast<double>(numerator)/denominator);Langage du code : PHP (php)

Good examples can be found on cppreference.com for both midpoint and lerp.

Share

,

  1. Pas encore de commentaire.
(ne sera pas publié)


Les commentaires sont fermés.