Skip to content

Instantly share code, notes, and snippets.

@sergey-shambir
Last active October 27, 2017 10:36
Show Gist options
  • Save sergey-shambir/685a64cfd57c5154c715c58647a58491 to your computer and use it in GitHub Desktop.
Save sergey-shambir/685a64cfd57c5154c715c58647a58491 to your computer and use it in GitHub Desktop.
Relative equal comparison
#include <cmath>
// Сравнение с допустимой абсолютной погрешностью
bool areCloseAbsolute(float a, float b, float tolerance = 0.001f)
{
return std::abs(a - b) < tolerance;
}
// Сравнение с допустимой относительной погрешностью
bool areCloseRelative(float a, float b, float tolerance = 0.001f)
{
return std::abs((a - b) / b) < tolerance;
}
// Сравнение двух чисел с плавающей точкой с допустимой погрешностью
bool areFuzzyEqual(float a, float b)
{
constexpr float tolerance = 0.001f;
if (std::abs(b) > 1.f)
{
return areCloseRelative(a, b, tolerance);
}
return areCloseAbsolute(a, b, tolerance);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment