When to use DBL_EPSILON / epsilon

DBL_EPSILON / std :: numeric_limits :: epsilon will give me the smallest value that will matter when added with one.

I am having trouble understanding how to apply this knowledge to something useful.

Epsilon is much more than the smallest value a computer can handle, so would it be a good guess that it is safe to use lower values ​​than epsilon?

If the relationship between the values ​​I'm working with is less than 1 / epsilon?

+4
source share
2 answers

The definition of DBL_EPSILON is wrong. This is the difference between the next representable number after 1 and 1 (your definition assumes that the rounding mode is set to "in the direction 0" or "minus infinity", which is not always true).

This is something useful if you know enough about numerical analysis. But I'm afraid this place is not the best to find out about it. As an example, you can use it when building a comparison function that would indicate that two floating point numbers are approximately equal, like this

bool approximatively_equal(double x, double y, int ulp) { return fabs(xy) <= ulp*DBL_EPSILON*max(fabs(x), fabs(y)); } 

(but without knowing how to determine ulp, you will be lost, and this function will probably have problems if the intermediate results are denormal; fp calculation is hard to make reliable)

+4
source

The difference between X and the next value of X changes in accordance with X
DBL_EPSILON is just the difference between 1 and the next value of 1 .

You can use std::nextafter to test two double with epsilon difference:

 bool nearly_equal(double a, double b) { return std::nextafter(a, std::numeric_limits<double>::lowest()) <= b && std::nextafter(a, std::numeric_limits<double>::max()) >= b; } 

If you want to test two double with a difference of * epsilon coefficient, you can use:

 bool nearly_equal(double a, double b, int factor /* a factor of epsilon */) { double min_a = a - (a - std::nextafter(a, std::numeric_limits<double>::lowest())) * factor; double max_a = a + (std::nextafter(a, std::numeric_limits<double>::max()) - a) * factor; return min_a <= b && max_a >= b; } 
+1
source

Source: https://habr.com/ru/post/1313752/


All Articles