This post stated that you shouldn't compare floating point variables with ==
because of rounding errors. What should I use then, and when?
Asked
Active
Viewed 135 times
-2

Community
- 1
- 1

MatthewRock
- 1,071
- 1
- 14
- 30
1 Answers
3
You could use something along the lines of
if (abs(result - expected) < 0.00001)
or for a relative, rather than absolute, error:
float relativeError = abs((A - B) / B);
if (relativeError <= maxRelativeError)
See this for more details. http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

Pedro
- 409
- 2
- 7
-
But beware. That "relativeError" calculation blows up if B is zero. In general, if you use relative errors, zero will only ever compare "nearly equal" to a value which is exactly zero. – Martin Bonner supports Monica Apr 04 '16 at 12:33