Last active
October 27, 2017 10:36
-
-
Save sergey-shambir/685a64cfd57c5154c715c58647a58491 to your computer and use it in GitHub Desktop.
Relative equal comparison
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 <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