subsurface/core/interpolate.h
Berthold Stoeger 1ccfb823f0 core: make interpolate() a template
Make the type the interpolate() function works on a template type,
so that this can be used for arbitrary unit types without warnings.
Internally, it does its math using floating point arithmetics anyway,
so no risk of overflow. (Exception: when just taking the middle point,
but I would hope that no part of the code lives on the edge such that
addition of two values gives an overflow.)

Moreover, add an "math.h" include so that the header becomes
independent of others.

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
2024-12-17 13:58:27 +13:00

24 lines
725 B
C++

// SPDX-License-Identifier: GPL-2.0
#ifndef INTERPOLATE_H
#define INTERPOLATE_H
#include <type_traits>
#include <math.h> // lrint()
/* Linear interpolation between 'a' and 'b', when we are 'part'way into the 'whole' distance from a to b
* Since we're currently stuck with C++17, we have this horrible way of testing whether the template
* parameter is an integral type.
*/
template <typename T,
std::enable_if_t<std::is_integral<T>::value, bool> = true>
T interpolate(T a, T b, int part, int whole)
{
/* It is doubtful that we actually need floating point for this, but whatever */
if (whole) {
double x = (double)a * (whole - part) + (double)b * part;
return (int)lrint(x / whole);
}
return (a+b)/2;
}
#endif