2

I tried to compile the following code.

x = 0
while x <= 1
    x = x+0.02
end

The last value of x that I should get is equal to 1.02 (which make a false condition in while loop)

However, I am very wondered that I always got the last value of x equal to 1 and the while loop is stopped. I don't know what's wrong with my code. Could anyone please help me find out?

  • Just for your information for someone who want to do a loop in float value condition, I have answered my question to do that by following code. x = 0 while x <= 1+4.4409e-16 x = x+0.02 end It's not quite good method, if someone has another solution, you can share it!, but it solved my question :-) –  Mar 25 '13 at 18:29

2 Answers2

5

0.02 cannot be represented exactly in a floating point binary number (double), so you'll get some rounding errors. The result is that you don't reach one, but a number which is slighly larget than one.

Try to append disp(x-1) after your code, to see that x is not exactly 1.

This site shows how 0.02 is represented in IEEE754 double precision floating point: http://www.binaryconvert.com/result_double.html?decimal=048046048050

The essential thing here is that it is a little bit larger than 0.02

One way to solve this would be to use an integer loop variable. It's still of type double, but it only has integer values, which don't have rounding issues unless you use very large numbers (>=2^56?)

for n=0:100
    x = n/100;
end
Kleist
  • 7,785
  • 1
  • 26
  • 30
  • Thank you very much @Kleist. It's surprised me !!. So, Could you please suggest me how can I edit my code to let my code run for the last time? –  Mar 24 '13 at 22:58
  • Added a solution to my answer. – Kleist Mar 24 '13 at 23:04
  • Your method is very well. However, I have to calculate a probability value, which absolutely has a type of double value, util the value <= 1. Then, I plot my graph. Is it possible to use double value loop variable? –  Mar 24 '13 at 23:15
0

Try format long before running you will get this:

x =  0.920000000000000
x =  0.940000000000001 
x =  0.960000000000001 
x =  0.980000000000001
x =  1.000000000000000

Note the 1 at the very end. 0.02 cannot be represented exactly with floating point arithmetic. So although it looks like 1 when you compare it, it is actually larger so it comes up as false and exists the loop.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • Thank you very much @Ben. Could you please give me some suggestions what I should edit in my code to run the last time? –  Mar 24 '13 at 23:03