PhilliP
PhilliP

Reputation: 73

I want to stop the code when x is equal to 1

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?

Upvotes: 3

Views: 117

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102309

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

Upvotes: 2

StaticBeagle
StaticBeagle

Reputation: 5175

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

Upvotes: 3

Related Questions