0

Even if the conditional statement of the while loop is true, the loop keeps looping!

this is the code (not the one I'm working on but it represents the same pbl):

counter = 0

while true
    counter = counter + .1
    if counter == 10
        break;
    end
end

Obviously the loop should stop when counter reaches 10, but that condition is never met

When using integers as increment it works as predicted.

  • 1
    100 * .1 is not equal to 10, see the linked duplicate for an explanation. You should always use integers as counters in loops, or use an inequality (`while counter<10`). – Cris Luengo Apr 14 '20 at 00:43
  • 1
    Thanks @CrisLuengo, The use of a floating point as increment was important for me. The inequality did the work! – Omar ELmekaalel Apr 14 '20 at 14:25
  • You can also write a loop over non-integer values like this: `for counter = 0:0.1:9.9`. That is a more robust method, it allows you to control exactly which values are used. As `0:0.1:0.99` is computed in a much more robust way than simply repeated additions of 0.1, you don't get any cumulative error in your counter. – Cris Luengo Apr 14 '20 at 14:31
  • Yes, that's more convenient way, but in my case I have to increment by .001 or lower to check the feasibility of an LMI, the code above was resuming the problem. Thanks again for the help! – Omar ELmekaalel Apr 14 '20 at 14:54

0 Answers0