EPSILON is the
smallest biggest number such that 1 + EPSILON still equals 1. There is a FLT_EPSILON for floats and DBL_EPSILON for doubles. The EPSILON's need to be scaled according to the number you have. If your number is 1000 say, then you need 1000 * DBL_EPSILON.
The thing to understand is the 'distance' between representable numbers over different ranges. If we consider a float that equals 1, the next greatest number that can represented is about 1 + 1E-8, so the 'distance' is 1E-8. If the float is 1E8, the next greater number is 1.0000001E8, so the distance is 1.0. At 1E9 the distance is 10, at 1E10 distance is 100. So when testing for equality you really need to test that your number is between the number below and the number above. That's where the EPSILON's come in. Similar for for less than and greater than.
The reason that inexact representation occurs, is because of the binary fractions that are used. A binary fraction of 1.1101 is 1 + 0.5 + 0.25 + 0.0625. USing this method it is possible to represent most of the numbers, but not all.
The other consideration is the precision of the answer that you require. Say you wish to use a prcision of 0.01, you can do this:
1 2 3 4 5 6 7 8
|
double MyPrecision = 0.01;
double MyDouble = 0.1; //not exact is about 0.0999...97 to 16 sig figures
double MyNum = 10 * MyDouble ; // not exact 0.999...97
if (MyNum > (1.0 - MyPrecision) && MyNum < 1.0 +MyPrecision ) //this is true
cout << "MyNum equals 1.0 0.01 precision" << endl;
else
cout << "MyNum is not equal to 1.0 0.01 precision" << endl;
|
This is OK but the 0.01 suffers from the same problem as other floating point numbers, so in some situations you might still need to use DBL_EPSILON as well.
Generally floating point is a pain in the A**, but you can get used to it.
Google some more there is heaps of stuff about this topic.
HTH Hope this helps