Although C provides the
== operator for use with
floating-point variables (
float and
double), and most
processor ISAs have instructions to support it, it is not the best way to
compare two numbers.
Real numbers are represented in processor registers by a finite number of bits. If you perform an operation that requires more bits in the answer than the processor has, you get an imprecise answer. This is normally alright, because the error appears in the least-significant bits.
However, for the operation of comparison, all bits are significant. If two numbers differ in the slightest, they appear unequal. Thus 1.0000001 - 1 will not reliably equal .0000001. Unless both operands are obvious sums of powers of two, the test will almost always fail in cases where promotion is required to compare a single-precision float to a double-precision double.
It would be nice if C did provide a useful comparison operator, but it doesn't. You just have to do it as subtraction and an absolute value.
if ( abs( a - b ) < .000001 ) SpinWheels();
Use your programming karma and do test runs to invent the proper margin of error.