Reputation: 21
I wrote a very simple matlab code which is;
b=4.7;
s=0;
while s <b
s=s+0.1
end
I expect s to be 4.7 but matlab gives 4.8. I am very suprised about this because calculatioun of 0.1 47 times should not give such error. It is a very simple math. Also, if I change b to 4.6 code works fine. I looked the s with format long and matlab gives s = 7.9999999999999. There is a very small error thats why code gives s = 4.8. What is the solution to this problem ? Should I be suspicious about matlab for simple calculations.
Upvotes: 2
Views: 39
Reputation: 21563
It was already indicated that the problem is due to floating point numbers. What you should realize, is that this is not because matlab does something strange, but that other languages that use floating point numbers will encounter exactly the same problem as some numbers simply cannot be stored exactly in this binary format. Here is a simple illustration, that can easily be reproduced in many programming languages:
0.3+0.3+0.3==0.9
This should return true, but unfortunately it returns false.
If you want to be reasonably safe that you do not run into this kind of problem, you should allow for a sufficiently large tolerance. However, you will also want this to be as small as possible to prevent different kinds of problems.
Here is a solution that automatically tries to allow a sensible tolerance:
b=4.7;
s=0;
tol = 100*eps(b);
while s <b-tol
s=s+0.1
end
Note that I would (in general) avoid using a while loop if I already know how often it needs to run. The following code is quite simple and less prone to errors:
for s=0:0.1:4.7
s
end
Upvotes: 1
Reputation: 63
I also think your problem is mainly about floating point errors.
Whenever I need it, I use following workaround:
b=4.7;
s=0;
dev = 1e-15; % Maximum deviation (example)
while b-s > dev
s=s+0.1
end
It runs the loop only 47 times and ends it when s = 4.7
Upvotes: 1