The for loop gives an odd number instead of 0?
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Stephen23
2015-11-9
编辑:Stephen23
2015-11-10
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!"
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!