Comparing Numerical Values
Jiro's pick this week isnumcmpbyCarlos Adrian Vargas Aguilera.
Some (many?) of you may have heard aboutissues with floating point math, and may have even readthis reference. Even in our blogs, many of us have written aboutfloating point arithmetic.
Here's a short example that illustrates this.
x = 2 - 1/3 - 1/3 - 1/3
x = 1.0000
But if we compare the result to its theoretical answer, we get that they aren't equal.
tf = isequal(x, 1)
tf = 0
If we displayxin hexadecimal format to inspect the full precision,
formathexx
x = 3ff0000000000001
On the other hand, the value "1" has a hexadecimal representation of
1
ans = 3ff0000000000000
Note the difference in the last bit.
Because of this, usually it is not a good practice to do a straight up comparison of floating point arithmetics. Instead you may do things like this.
formatshorttf = abs(x - 1) <= eps(1)
tf = 1
Carlos'snumcmp所有ows you to compare two values within a specific tolerance. You can choose from a set of various comparisons, such as '==', '~=', '<', '>', etc. You can also select the tolerance, specified by a positive integerTOLwhich represents10^(-TOL).
tf = numcmp(x,'==',1,10)% tolerance of 1e-10
tf = 1
Thanks for the entry, Carlos. One comment. I like that it is vectorized, but you userepmatto match the size of the inputs. You even have a note saying that you "avoided usingbsxfun". I actually recommend usingbsxfun. It is much more efficient in terms of speed and memory, especially for larger data.
Comments
Give this a try, and let us know what you thinkhereor leave acommentfor Carlos
- Category:
- Picks
Comments
To leave a comment, please clickhereto sign in to your MathWorks Account or create a new one.