{"id":7468,"date":"2016-05-27T09:00:35","date_gmt":"2016-05-27T13:00:35","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=7468"},"modified":"2016-05-27T06:39:50","modified_gmt":"2016-05-27T10:39:50","slug":"comparing-numerical-values","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2016\/05\/27\/comparing-numerical-values\/","title":{"rendered":"Comparing Numerical Values"},"content":{"rendered":"\r\n<div class=\"content\"><p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/15007\">Jiro<\/a>'s pick this week is <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/21190-numcmp-m\">numcmp<\/a> by <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/869698\">Carlos Adrian Vargas Aguilera<\/a>.<\/p><p>Some (many?) of you may have heard about <a href=\"https:\/\/en.wikipedia.org\/wiki\/Floating_point#Accuracy_problems\">issues with floating point math<\/a>, and may have even read <a href=\"https:\/\/docs.oracle.com\/cd\/E19957-01\/806-3568\/ncg_goldberg.html\">this reference<\/a>. Even in our blogs, many of us have written about <a href=\"https:\/\/www.mathworks.com\/search\/site_search.html?q=floating+point+arithmetic&amp;c%5B%5D=blogs\">floating point arithmetic<\/a>.<\/p><p>Here's a short example that illustrates this.<\/p><pre class=\"codeinput\">x = 2 - 1\/3 - 1\/3 - 1\/3\r\n<\/pre><pre class=\"codeoutput\">x =\r\n    1.0000\r\n<\/pre><p>But if we compare the result to its theoretical answer, we get that they aren't equal.<\/p><pre class=\"codeinput\">tf = isequal(x, 1)\r\n<\/pre><pre class=\"codeoutput\">tf =\r\n     0\r\n<\/pre><p>If we display <tt>x<\/tt> in hexadecimal format to inspect the full precision,<\/p><pre class=\"codeinput\">format <span class=\"string\">hex<\/span>\r\nx\r\n<\/pre><pre class=\"codeoutput\">x =\r\n   3ff0000000000001\r\n<\/pre><p>On the other hand, the value \"1\" has a hexadecimal representation of<\/p><pre class=\"codeinput\">1\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n   3ff0000000000000\r\n<\/pre><p>Note the difference in the last bit.<\/p><p>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.<\/p><pre class=\"codeinput\">format <span class=\"string\">short<\/span>\r\ntf = abs(x - 1) &lt;= eps(1)\r\n<\/pre><pre class=\"codeoutput\">tf =\r\n     1\r\n<\/pre><p>Carlos's <tt>numcmp<\/tt> allows you to compare two values within a specific tolerance. You can choose from a set of various comparisons, such as '==', '~=',  '&lt;',  '&gt;', etc. You can also select the tolerance, specified by a positive integer <tt>TOL<\/tt> which represents <tt>10^(-TOL)<\/tt>.<\/p><pre class=\"codeinput\">tf = numcmp(x,<span class=\"string\">'=='<\/span>,1,10)      <span class=\"comment\">% tolerance of 1e-10<\/span>\r\n<\/pre><pre class=\"codeoutput\">tf =\r\n     1\r\n<\/pre><p>Thanks for the entry, Carlos. One comment. I like that it is vectorized, but you use <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/repmat.html\"><tt>repmat<\/tt><\/a> to match the size of the inputs. You even have a note saying that you \"avoided using <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/bsxfun.html\"><tt>bsxfun<\/tt><\/a>\". I actually recommend using <tt>bsxfun<\/tt>. It is much more efficient in terms of speed and memory, especially for larger data.<\/p><p><b>Comments<\/b><\/p><p>Give this a try, and let us know what you think <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=7468#respond\">here<\/a> or leave a <a href=\"http:\/\/jp.mathworks.com\/matlabcentral\/fileexchange\/21190#comments\">comment<\/a> for Carlos<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_0569c8a279c64597b9bd36c8f372d575() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='0569c8a279c64597b9bd36c8f372d575 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 0569c8a279c64597b9bd36c8f372d575';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        copyright = 'Copyright 2016 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\r\n    }   \r\n     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_0569c8a279c64597b9bd36c8f372d575()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2016a<br><\/p><p class=\"footer\"><br>\r\n      Published with MATLAB&reg; R2016a<br><\/p><\/div><!--\r\n0569c8a279c64597b9bd36c8f372d575 ##### SOURCE BEGIN #####\r\n%%\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/15007\r\n% Jiro>'s pick this week is\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/21190-numcmp-m numcmp> by\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/869698 Carlos\r\n% Adrian Vargas Aguilera>.\r\n%\r\n% Some (many?) of you may have heard about\r\n% <https:\/\/en.wikipedia.org\/wiki\/Floating_point#Accuracy_problems issues\r\n% with floating point math>, and may have even read\r\n% <https:\/\/docs.oracle.com\/cd\/E19957-01\/806-3568\/ncg_goldberg.html this\r\n% reference>. Even in our blogs, many of us have written about\r\n% <https:\/\/www.mathworks.com\/search\/site_search.html?q=floating+point+arithmetic&c%5B%5D=blogs\r\n% floating point arithmetic>.\r\n%\r\n% Here's a short example that illustrates this.\r\n\r\nx = 2 - 1\/3 - 1\/3 - 1\/3\r\n\r\n%%\r\n% But if we compare the result to its theoretical answer, we get that they\r\n% aren't equal.\r\n\r\ntf = isequal(x, 1)\r\n\r\n%%\r\n% If we display |x| in hexadecimal format to inspect the full precision,\r\n\r\nformat hex\r\nx\r\n\r\n%%\r\n% On the other hand, the value \"1\" has a hexadecimal representation of\r\n\r\n1\r\n\r\n%%\r\n% Note the difference in the last bit.\r\n%\r\n% Because of this, usually it is not a good practice to do a straight up\r\n% comparison of floating point arithmetics. Instead you may do things like\r\n% this.\r\n\r\nformat short\r\ntf = abs(x - 1) <= eps(1)\r\n\r\n%%\r\n% Carlos's |numcmp| allows you to compare two values within a specific\r\n% tolerance. You can choose from a set of various comparisons, such as\r\n% '==', '~=',  '<',  '>', etc. You can also select the tolerance, specified\r\n% by a positive integer |TOL| which represents |10^(-TOL)|.\r\n\r\ntf = numcmp(x,'==',1,10)      % tolerance of 1e-10\r\n\r\n%%\r\n% Thanks for the entry, Carlos. One comment. I like that it is vectorized,\r\n% but you use <https:\/\/www.mathworks.com\/help\/matlab\/ref\/repmat.html\r\n% |repmat|> to match the size of the inputs. You even have a note saying\r\n% that you \"avoided using\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/bsxfun.html |bsxfun|>\". I\r\n% actually recommend using |bsxfun|. It is much more efficient in terms of\r\n% speed and memory, especially for larger data.\r\n%\r\n% *Comments*\r\n%\r\n% Give this a try, and let us know what you think\r\n% <https:\/\/blogs.mathworks.com\/pick\/?p=7468#respond here> or leave a\r\n% <http:\/\/jp.mathworks.com\/matlabcentral\/fileexchange\/21190#comments\r\n% comment> for Carlos\r\n\r\n##### SOURCE END ##### 0569c8a279c64597b9bd36c8f372d575\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\nJiro'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,... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2016\/05\/27\/comparing-numerical-values\/\">read more >><\/a><\/p>","protected":false},"author":35,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/7468"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=7468"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/7468\/revisions"}],"predecessor-version":[{"id":7470,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/7468\/revisions\/7470"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=7468"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=7468"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=7468"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}