Created
November 24, 2017 23:15
-
-
Save MathyV/38ac64eac2518cdb5811e720efe09ce4 to your computer and use it in GitHub Desktop.
Double comparison with configurable precision in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef DOUBLEEQUALS_H | |
#define DOUBLEEQUALS_H | |
#include <cmath> | |
class DoubleEquals | |
{ | |
private: | |
static constexpr int defaultPrecision = 8; | |
static constexpr double get_precision(int n) | |
{ | |
return n == 0 ? 1.0 : 0.1 * get_precision(n - 1); | |
} | |
public: | |
template<int N> | |
static bool ComparePrecision(double a, double b) | |
{ | |
constexpr double precision = get_precision(N); | |
return std::fabs(a - b) < precision; | |
} | |
static auto constexpr Compare = &ComparePrecision<defaultPrecision>; | |
}; | |
#endif //DOUBLEEQUALS_H |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "DoubleEquals.h" | |
int main(void) | |
{ | |
double a = 0.1; | |
double b = 0.1000000001; | |
if (DoubleEquals::Compare(a, b)) | |
{ | |
// Should be true | |
} | |
if (DoubleEquals::ComparePrecision<12>(a, b)) | |
{ | |
// Should be false | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment