As What Every Computer Scientist Should Know About Floating-Point Arithmetic explains, floating point numbers in computer programs pretend they can represent any real number, but actually have only 32 or 64 bits, so you will get rounded off to the nearest representation. Even numbers that look simple, like 0.1, have an endless representation in binary and so will get rounded off. Functions that operate on floating point numbers like cos
and pow
will, by their nature, sometimes give you the 'wrong' result simply because the 'right' result is not a representible floating point.
Sometimes the solution is complex. However in this case the solution is quite simple - check that the two numbers' difference is less than epsilon, where epsilon is a small enough number to give you the accuracy you need. e.g.
float epsilon = 0.0001;
if(abs(b-a) < epsilon)
Also, whenever you need accuracy more than speed and size, use double
in preference to float
. It's twice as big and thus many significant places more precise.