Every time I start a new project and when I need to compare some float or double variables I write the code like this one:
if (fabs(prev.min[i] - cur->min
You can use std::nextafter
for testing two double
with the smallest epsilon on a value (or a factor of the smallest epsilon).
bool nearly_equal(double a, double b)
{
return std::nextafter(a, std::numeric_limits::lowest()) <= b
&& std::nextafter(a, std::numeric_limits::max()) >= b;
}
bool nearly_equal(double a, double b, int factor /* a factor of epsilon */)
{
double min_a = a - (a - std::nextafter(a, std::numeric_limits::lowest())) * factor;
double max_a = a + (std::nextafter(a, std::numeric_limits::max()) - a) * factor;
return min_a <= b && max_a >= b;
}