-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapproximatelyEqualRel.cpp
More file actions
44 lines (35 loc) · 1.5 KB
/
Copy pathapproximatelyEqualRel.cpp
File metadata and controls
44 lines (35 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <algorithm>
#include <iostream>
// Our own constexpr implementation of std::abs (for use in C++14/17/20)
// In C++23, use std::abs
// constAbs() can be called like a normal function, but can handle different types of values (e.g. int, double, etc...)
template <typename T>
constexpr T constAbs(T x)
{
return (x < 0 ? -x : x);
}
// Return true if the difference between a and b is within epsilon percent of the larger of a and b
constexpr bool approximatelyEqualRel(double a, double b, double relEpsilon)
{
return (constAbs(a - b) <= (std::max(constAbs(a), constAbs(b)) * relEpsilon));
}
// Return true if the difference between a and b is less than or equal to absEpsilon, or within relEpsilon percent of the larger of a and b
constexpr bool approximatelyEqualAbsRel(double a, double b, double absEpsilon, double relEpsilon)
{
// Check if the numbers are really close -- needed when comparing numbers near zero.
if (constAbs(a - b) <= absEpsilon)
return true;
// Otherwise fall back to Knuth's algorithm
return approximatelyEqualRel(a, b, relEpsilon);
}
int main()
{
// a is really close to 1.0, but has rounding errors
constexpr double a{ 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 };
constexpr double relEps { 1e-8 };
constexpr double absEps { 1e-12 };
std::cout << std::boolalpha; // print true or false instead of 1 or 0
constexpr bool same { approximatelyEqualAbsRel(a, 1.0, absEps, relEps) };
std::cout << same << '\n';
return 0;
}