Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab evaluates 0.9<0.9 to `True`

Tags:

matlab

Below is my matlab code snippet:

clear all;
x0=0.5;
x2=1.4;
h=0.1;
while(x0<x2)
    x0=x0+0.1;
end
x0

There is no doubt that the result of x0 is 1.4, what confused me is when I replace x2=1.4 to x2=0.8, 0.9, 1.0, 1.1, or 1.2(anyone of them) the result becomes incorrect.

For example, x2=0.9 will makes the code generate x0=1.0 instead of x0=0.9. And I find the fact that during the process with x0 increases to 0.9 then x0<x2(0.9<0.9) will yeild 1(True) which is definitely wrong.

What's going on here?

like image 533
withparadox2 Avatar asked Dec 09 '25 05:12

withparadox2


2 Answers

I would like to extend Dan's answer a little. Run this code:

clear all;
x0=0.5;
x2=0.9;
h=0.1;
while(x0<x2)
    x0=x0+0.1;
    disp(x2-x0); % <-- I added this line
end
x0

Output (ideone):

0.30000
0.20000
0.10000
1.1102e-16
-0.100000
x0 =  1.00000

The 4th line of the output shows the rounding error: after adding 0.1 to 0.5 four times, the result will be less than 0.9: the difference is 1.1102e-16. That's why x0 will be 1.0 in the end.

like image 57
kol Avatar answered Dec 11 '25 22:12

kol


Basically you should never compare floating point numbers directly. See this link provided by Sam Roberts to better understand this.

In binary, 0.1 becomes a recurring decimal which your computer eventually has to truncate. So you aren't really adding 0.1 and that rounding error compounds each time you add 0.1 eventually leading to your comparison missing. So you are not actually evaluating 0.9<0.9 but rather the sum of a truncated conversion to binary of 0.1 9 times with the truncated binary version of 0.9. The numbers won't be the same.

like image 32
Dan Avatar answered Dec 11 '25 21:12

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!