Possible Duplicate:
Most effective way for float and double comparison
I am new to C++. I had a doubt, while reading C++. How to decide two floating point numbers equal to each other or not ?
Thanks in advance
Possible Duplicate:
Most effective way for float and double comparison
I am new to C++. I had a doubt, while reading C++. How to decide two floating point numbers equal to each other or not ?
Thanks in advance
There is a special constant you need to know of, called DBL_EPSILON (or FLT_EPSILON). This is the smallest value that could be added to 1.0 and change its value. The value 1.0 is very important — larger numbers do not change when added to DBL_EPSILON. Now, you can scale this value to the numbers you are comparing to tell whether they are different or not. The correct expression for comparing two doubles is:
if (fabs(a-b) <= DBL_EPSILON * fmax(fabs(a), fabs(b)))
{
// ...
}
If your floating point types use IEEE 754 representation (most likely this is the case), then you should use the fact that the ordering of the binary representation of floats is the same as the ordering by value. That is, if you increment the binary representation of a float by one bit, you get the next larger number.
Using this fact, we can compare floats by counting their binary difference. This is called "comparison by unit-in-last-place (ULP)". There are some subtleties involving signs, zeros, infinities and NaNs, but that's the gist of it. Here is a comprehensive article explaining this.
Basically, we consider two floats equal if they differ in some small number of units in last place. Together with your compiler's documentation of its math functions' accuracies in last place and your own code you can determine which cut-off suits your needs.
In pseudo code:
double x, y;
// this is type punning, should be done differently in reality
uint64_t ux = *reinterpret_cast<const uint64_t*>(&x);
uint64_t uy = *reinterpret_cast<const uint64_t*>(&y);
return abs(ux - uy) < CUT_OFF; // e.g. CUT_OFF = 3;
The above code is just a crude example which won't work, you have to take care of lots of special cases before this final comparison. See the article for details.
Obviously, you should not use operator ==
to compare them.
The important concept here is if the difference of your two floating point number is small enough to the precision requirement of your problem to solve or smaller than your error range, we should consider them as equal.
There are some practical methods suggestions such as
fabs(f1 - f2) < precision-requirement
fabs(f1 - f2) < max(fabs(f1), fabs(f2)) * percentage-precision-requirement