floating point comparisons

Special K

Diamond Member
Jun 18, 2000
7,098
0
76
I know it's bad to make direct comparisons between floating point numbers in C, and that instead you should do something like:

if (float_1 - float_2 < ...)

to test for equality, that is, if float_1 - float_2 is smaller than some number, then you assume the numbers are equal. My question is what number do I compare against? How small a number do I have to use to ensure the 2 numbers are equal?
 

PrincessGuard

Golden Member
Feb 5, 2001
1,435
0
0
The answer is: it depends. You have to look at the range of numbers you expect to get, and set the error to what your specific application deems reasonable.

You're doing what's called an epsilon comparison, which is generally not a good idea if you're dealing with numbers more than a few orders of magnitude apart. If you make epsilon small, 2 "equal" floats with large exponents will fail the test. If you make it large, 2 "equal" floats with small exponents will fail the test.

See http://www.cygnus-software.com...ts/comparingfloats.htm for more info.