フィルターのクリア

The for loop gives an odd number instead of 0?

1 回表示 (過去 30 日間)
sama
sama 2015 年 11 月 9 日
コメント済み: sama 2015 年 11 月 16 日
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

採用された回答

Stephen23
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!"
  1 件のコメント
sama
sama 2015 年 11 月 16 日
Thanks a lot

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by