The for loop gives an odd number instead of 0?

2 views (last 30 days)
Hello, I have a easy question but it is making me crazy.I have a for loop as follow:
zr4=1.1;zr2=-0.1;
KK=0.1;
for LL=1:DD
zr2=zr2+KK;
zr4=zr4-KK;
.......
end
When I see the result, Zr4 is changing from 1 to 1.3878e-16. I am so confused. after 0.1 instead of giving 0, it gives 1.3878e-16. I appreciate if you help me. Thanks

Accepted Answer

Stephen23
Stephen23 on 9 Nov 2015
Edited: Stephen23 on 10 Nov 2015
Floating point numbers are how decimal values are stored in your computer: they do not have infinite precision, and they can only approximate many values. Even if it looks like the "actual" value is being shown to you this does not mean that the internal representation inside your computer is the same value.
Lets have a quick look at those values:
>> zr4=1.1;
>> zr2=-0.1;
>> fprintf('%.30f\n',zr4)
1.100000000000000100000000000000
>> fprintf('%.30f\n',zr2)
-0.100000000000000010000000000000
Do you see that the trailing digits are not all zero. This means it is not possible to store them exactly using the binary numbers that computers use (unless you have infinite binary digits stored in infinite memory). This is not a problem with MATLAB, this is simply how all (binary) computers store numbers.
Of course this means that every operation you perform on floating point values will accumulate these errors. It is up to you (and every other programmer) to design programs that take this "floating point error" into account.
Read all about it:
And if you want to see what the decimal equivalent of a floating point value is, then try this FEX submission:
As its author points out: "Don't confuse the exact conversion with significance!"

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!