Skip to content

Instantly share code, notes, and snippets.

@MathyV
Created November 24, 2017 23:15
Show Gist options
  • Save MathyV/38ac64eac2518cdb5811e720efe09ce4 to your computer and use it in GitHub Desktop.
Save MathyV/38ac64eac2518cdb5811e720efe09ce4 to your computer and use it in GitHub Desktop.
Double comparison with configurable precision in C++
#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
#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