Move Vectormath main
C++20 game and graphics mathematics
Loading...
Searching...
No Matches
Tolerance.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <cmath>
5#include <limits>
6#include <type_traits>
7
8namespace mv::math
9{
10 template <typename T>
11 requires std::is_floating_point_v<T>
12 struct Tolerance
13 {
18
19 [[nodiscard]] static constexpr Tolerance Default() noexcept
20 {
21 return {std::numeric_limits<T>::epsilon() * T(4),
22 std::numeric_limits<T>::epsilon() * T(4),
23 std::numeric_limits<T>::epsilon() * T(16),
24 std::sqrt(std::numeric_limits<T>::epsilon())};
25 }
26 };
27
28 template <typename T>
29 requires std::is_floating_point_v<T>
30 [[nodiscard]] constexpr bool IsNearlyEqual(
31 T left,
32 T right,
34 {
35 if (left == right)
36 {
37 return true;
38 }
39 if (!std::isfinite(left) || !std::isfinite(right))
40 {
41 return false;
42 }
43
44 // The combined relative/absolute bound follows PEP 485 (2015),
45 // section 11; Move exposes both tolerances instead of hiding them.
46 const T difference = std::abs(left - right);
47 const T scale = std::max(std::abs(left), std::abs(right));
48 return difference <=
49 std::max(tolerance.Absolute, tolerance.Relative * scale);
50 }
51
52 template <typename T>
53 requires std::is_floating_point_v<T>
54 [[nodiscard]] constexpr bool IsNearlyZero(
55 T value,
56 T absoluteTolerance = Tolerance<T>::Default().Absolute) noexcept
57 {
58 return std::isfinite(value) && std::abs(value) <= absoluteTolerance;
59 }
60} // namespace mv::math
bool IsNearlyEqual(const Quat< T > &left, const Quat< T > &right, Tolerance< T > tolerance=Tolerance< T >::Default()) noexcept
Definition Quat.hpp:176
constexpr bool IsNearlyZero(T value, T absoluteTolerance=Tolerance< T >::Default().Absolute) noexcept
Definition Tolerance.hpp:54
static constexpr Tolerance Default() noexcept
Definition Tolerance.hpp:19