Skip to content

Instantly share code, notes, and snippets.

@ifarbod
Created October 20, 2019 18:36
Show Gist options
  • Save ifarbod/68a4d421ed9b737e02c094d76e58fae8 to your computer and use it in GitHub Desktop.
Save ifarbod/68a4d421ed9b737e02c094d76e58fae8 to your computer and use it in GitHub Desktop.
// from this
template <typename T, typename U>
inline T Lerp(const T& a, const T& b, const U& t)
{
return a * (1.0 - t) + b * t;
}
// to this:
template <typename T>
inline constexpr std::enable_if_t<std::is_floating_point_v<T>, T> Lerp(T a, T b, T t)
{
if (isnan(a) || isnan(b) || isnan(t))
{
return std::numeric_limits<T>::quiet_NaN();
}
else if ((a <= T{0} && b >= T{0}) || (a >= T{0} && b <= T{0}))
{
// ab <= 0 but product could overflow.
// return a * (T(1) - t) + b * t;
return t * b + (T{1} - t) * a;
}
else if (t == T{1})
{
return b;
}
else
{
// monotonic near t == 1.
const auto x = a + t * (b - a);
return (t > T{1}) == (b > a) ? Max(b, x) : Min(b, x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment