0

I have this code in matlab, it's very simple, but for some odd reason not working:

h = 0.01;
h0 = 0;

while 1

     h0 = h0 + h;

     if h0 == 1.000;
           display('nice')
           break;
     end
end

The point is for h0 to keep increasing by 0.01, and the if statement checks if h0 is 1 everytime. Once it is 1, the loop should be ended. The issue is that once h0 finally is 1, the if statement is not entered.

I tried changing the if condition to a bunch of different values, such as 0.04,or 0.1. I found it also doesn't work for 0.06, and anything over 0.1.

I have no clue why this isn't working, it's a simple if statement and should work.

itsnewton
  • 1
  • 2
  • I would guess there's a flaw in the if statement somewhere but since it works for values like 0.05 and 0.07, but not for 0.06, I just have no clue – itsnewton Apr 06 '21 at 22:42
  • 1
    Try displaying the values of `h0` (remove the semicolon in `h0 = h0 + h`) with `format long`, and you'll see that `h0` never equals `1` exactly. This is due to [floating-point inaccuracies](https://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab) – Luis Mendo Apr 06 '21 at 22:45
  • Yep I'll take a look. Thanks – itsnewton Apr 06 '21 at 22:50

0 Answers0