···1515very small. The error margin that the difference is compared to is often called *epsilon*.
1616The most simple form:
17171818- if( a-b < 0.00001) // wrong - don't do this
1818+ if( Math.abs(a-b) < 0.00001) // wrong - don't do this
19192020This is a bad way to do it because a fixed epsilon chosen because it "looks small" could actually be way too
2121large when the numbers being compared are very small as well. The comparison would return "true" for numbers that are quite different. And when the numbers are very large, the epsilon
2222could end up being smaller than the smallest rounding error, so that the comparison always returns "false".
2323Therefore, it is necessary to see whether the *relative error* is smaller than epsilon:
24242525- if( (a-b)/b < 0.00001 ) // still not right!
2525+ if( Math.abs((a-b)/b) < 0.00001 ) // still not right!
26262727There is one important special case where this will fail: When both a and be are zero. 0.0/0.0 is "not a number", which returns false for all comparisons. So we have to take care of that first:
28282929- if( a==b || (a-b)/b < 0.00001 ) // more correct, but bad design
2929+ if( a==b || Math.abs((a-b)/b) < 0.00001 ) // more correct, but bad design
30303131Since it's not immediately clear what this code does, it should be done in a function or method:
32323333 function nearlyEqual(a,b)
3434 {
3535- return a==b || (a-b)/b < 0.00001;
3535+ return a==b || Math.abs((a-b)/b) < 0.00001;
3636 }
37373838 if(nearlyEqual(a,b))