Domanda

When I read a book today, I found the following code to check whether two lines intersect:

struct Line{
    static double epsilon = 0.000001;   
    double slope;
    double yintercept;
};

bool intersect(Line& line_1, Line& line_2)
{
    bool ret_1 = abs(line_1.slope - line_2.slope) > epsilon;
    bool ret_2 = abs(line_1.yintercept - line_2.yintercept) < epsilon;

    return ret_1 || ret_2;
}

The program uses slope and y-intercept to determine whether two line intersect. However, I am confusing here why we need epsilon? Why cannot directly make use of '==' here?

There is a common below this method. The author says never check for equality with ==. Instead, check if the difference is less than an epsilon value.

È stato utile?

Soluzione

Some decimal numbers can only be represented with a certain precision on a system. In the case of normal floating point numbers that precision depends on the format of the number (usually IEEE 754). Hardware differences and base constraints can introduce small rounding errors.

There are also other factors which might come into play: when dealing with software floating point calculations you might get irrational numbers or numbers too small to deal with full-precision calculations (i.e. subnormals or denormals). Some compilers treat them as allowed while others flush the result to zero. And some systems also use the so-called fast-math calculation which allows faster results by using hardware circuitry which works with less precision.

All these behaviors force you to put an epsilon, a "tolerance" threshold that covers you by the approximation errors.

If you're dealing with floating point calculations I strongly recommend reading http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top