3

I used Octave to write this code.

x=0.0;   
while (x~=1.0)
  x=x+0.1;
  fprintf('x=%20.18f\n',x)
  pause
endwhile

I want to stop the code when x is equal to 1. So, I put some code like this

x=0.0;   
while (x~=1.0)
   x=x+0.1;
   fprintf('x=%20.18f\n',x)
   if abs(x-1)<(eps/2),
      print(x)
   endif
   pause
endwhile

But it did not work, and show numbers infinitely. How can I write a code to stop this code when x is equal to 1?

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
PhilliP
  • 73
  • 1
  • 8

2 Answers2

3

When you add:

x = 0.0;
x = x + 0.1;

You can end up with x = 0.100000000000000006 for example due to numerical precision so the while will never exit since it's always going to be different than 1.

You can use the less than < operator to stop the loop when x is equal to 1:

x=0.0;   
while (x < 1.0)
   x=x+0.1;
   fprintf('x=%20.18f\n',x)
   if abs(x-1)<(eps/2),
      print(x)
   endif
   pause
endwhile
StaticBeagle
  • 5,070
  • 2
  • 23
  • 34
2

Perhaps you can try using an iterator k for while loop, rather than x itself, i.e.,

k = 0;
x = 0.0;   
while (k~=round(1.0/0.1))
  k += 1;
  x += 0.1;
  fprintf('x=%20.18f\n',x);
endwhile
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • @CrisLuengo Thanks for your feedback. Yes, I tried it and found that `1.0/0.1` is identical to `10`. Anyway, to play it safe, maybe `round(1.0/0.1)` would be better. – ThomasIsCoding Mar 05 '21 at 09:01
  • Anyway your advice here is the best, always use an integer as a loop variable. If you know the number of iterations it’s easier: `for x=0:0.1:1`, which is [designed to reach 1 at the end if x gets sufficiently close](https://stackoverflow.com/q/49377234/7328782). – Cris Luengo Mar 05 '21 at 15:14
  • @CrisLuengo Yes, agree, `for` should be a better option if the number of iterations is known. – ThomasIsCoding Mar 05 '21 at 15:44