File Exchange Pick of the Week

Our best user submissions

Comparing Numerical Values

Jiro's pick this week is numcmp by Carlos Adrian Vargas Aguilera.

Some (many?) of you may have heard about issues with floating point math, and may have even read this reference. Even in our blogs, many of us have written about floating 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 display x in hexadecimal format to inspect the full precision,

format hex
x
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.

format short
tf = abs(x - 1) <= eps(1)
tf =
     1

Carlos's numcmp allows 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 integer TOL which represents 10^(-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 use repmat to match the size of the inputs. You even have a note saying that you "avoided using bsxfun". I actually recommend using bsxfun. 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 think here or leave a comment for Carlos




Published with MATLAB® R2016a

|

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.