2

I am trying to understand the while statement in MatLab so this is what I did:

i=0;
while i<=20
  disp(i)
  i=i+1;
end

and as I expected, MatLab displayed numbers 0-20. However with this one:

j=0;
while j<=2
  disp(j)
  j=j+0.1;
end

MatLab only displays numbers 0-1.9. I expected to see numbers 0-2; what am I doing wrong here?

user172675
  • 69
  • 1
  • 6
  • 3
    Hint: type `j-2` after the second loop – Luis Mendo Mar 27 '15 at 16:28
  • Can you explain why? – user172675 Mar 27 '15 at 16:29
  • 5
    [Here](http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab) is the answer. With `double` precision variables, integers are represented exactly up to about 2^52 (off the top of my head), but other numbers aren't. That's why the first loop works and the second doesn't – Luis Mendo Mar 27 '15 at 16:30

0 Answers0