# About numerical difficulty of equality comparison operation between two double real numbers in Matlab

18 views (last 30 days)
Heng on 7 Jul 2014
Commented: Image Analyst on 12 Jul 2014
Assume we have two double real numbers a and b. a==b is the comparison operation used in Matlab to test equality. However, due to numerical issues, sometimes a and b obtained by some steps of calculation are theoretically equal but practically have a very small distance in magnitude of, say, 10^(-12). I know to compare two real numbers in practical coding, we should use something like abs(a-b)<10^(-12). I submit this thread to ask three questions:
(1) Does matlab just use a naive bit-wise comparison between floating point representations of two real numbers?
(2) If matlab internally use abs(a-b)<10^(-12) or something to implement == operation, is there any switch to control the threshold (10^(-12) in this example)?
(3) if assumption in (1) is true, since direct use of == takes a risk of producing unexpected result, why not deprecate == operator in matlab regarding real numbers to save programmer's precious time of debugging, or change it to the way described in (2)?
Thank you.

John D'Errico on 7 Jul 2014
Edited: John D'Errico on 7 Jul 2014
Yes. MATLAB uses a simple test for equality. It cannot be otherwise. Two numbers are equal, OR they are not. Otherwise there would be immense numbers of problems. If YOU wish to use a tolerance, it is trivial to implement. (Why is this a problem?)
Just because you want a fuzzy test for equality to be the default is not enough to make it a good idea in general.
As for the idea of saving programmer time in debugging, as long as one understands floating point arithmetic, I see no reason why it would save any time at all. In fact, it would introduce difficult to find bugs of a different sort. The novices to programming/numerical analysis will always have problems with floating point until they learn enough about it to survive, regardless of how you define such tests.
Finally, NEVER test for exact equality unless you know what is happening in the code. And if you don't know what is happening in your code, then it is time to start learning to write better code!
Image Analyst on 12 Jul 2014

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!