diff --git a/headers/vmath.hpp/vmath_fun.hpp b/headers/vmath.hpp/vmath_fun.hpp index 65350fa..c35ff4c 100644 --- a/headers/vmath.hpp/vmath_fun.hpp +++ b/headers/vmath.hpp/vmath_fun.hpp @@ -339,13 +339,22 @@ namespace vmath_hpp template < typename T > [[nodiscard]] std::enable_if_t, T> constexpr distance(T x, T y) noexcept { - return length(y - x); + if constexpr ( std::is_unsigned_v ) { + return x < y ? (y - x) : (x - y); + } else { + return length(x - y); + } } template < typename T > [[nodiscard]] std::enable_if_t, T> constexpr distance2(T x, T y) noexcept { - return length2(y - x); + if constexpr ( std::is_unsigned_v ) { + const T d = x < y ? (y - x) : (x - y); + return d * d; + } else { + return length2(x - y); + } } template < typename T > @@ -396,11 +405,7 @@ namespace vmath_hpp template < typename T > [[nodiscard]] std::enable_if_t, bool> constexpr approx(T x, T y, T epsilon) noexcept { - if constexpr ( std::is_unsigned_v ) { - return (x < y ? (y - x) : (x - y)) <= epsilon; - } else { - return abs(x - y) <= epsilon; - } + return distance(x, y) <= epsilon; } template < typename T > diff --git a/headers/vmath.hpp/vmath_vec_fun.hpp b/headers/vmath.hpp/vmath_vec_fun.hpp index 2667114..02c13de 100644 --- a/headers/vmath.hpp/vmath_vec_fun.hpp +++ b/headers/vmath.hpp/vmath_vec_fun.hpp @@ -954,12 +954,12 @@ namespace vmath_hpp template < typename T, std::size_t Size > [[nodiscard]] constexpr T distance(const vec& xs, const vec& ys) { - return length(ys - xs); + return length(xs - ys); } template < typename T, std::size_t Size > [[nodiscard]] constexpr T distance2(const vec& xs, const vec& ys) { - return length2(ys - xs); + return length2(xs - ys); } template < typename T, typename U diff --git a/untests/vmath_fun_tests.cpp b/untests/vmath_fun_tests.cpp index d020eb1..be59f6c 100644 --- a/untests/vmath_fun_tests.cpp +++ b/untests/vmath_fun_tests.cpp @@ -120,9 +120,17 @@ TEST_CASE("vmath/fun") { STATIC_CHECK(rlength2(10.f) == uapprox(0.01f)); STATIC_CHECK(rlength2(-10.f) == uapprox(0.01f)); + STATIC_CHECK(distance(5, 10) == 5); + STATIC_CHECK(distance(10, 5) == 5); + STATIC_CHECK(distance(5u, 10u) == 5); + STATIC_CHECK(distance(10u, 5u) == 5); STATIC_CHECK(distance(5.f, 10.f) == uapprox(5.f)); STATIC_CHECK(distance(-5.f, -10.f) == uapprox(5.f)); + STATIC_CHECK(distance2(5, 10) == 25); + STATIC_CHECK(distance2(10, 5) == 25); + STATIC_CHECK(distance2(5u, 10u) == 25); + STATIC_CHECK(distance2(10u, 5u) == 25); STATIC_CHECK(distance2(5.f, 10.f) == uapprox(25.f)); STATIC_CHECK(distance2(-5.f, -10.f) == uapprox(25.f));