Numerical issue in simple summation/addition

below code prints 1. But if you have b = 0.2 at the second line, it does not print 1.
a = 0;
b = 0.1;
c = a;
while c < 1
c
c = c+b;
end

その他の回答 (2 件)

Image Analyst
Image Analyst 2016 年 1 月 23 日

1 投票

It has nothing to do with the version. It has everything to do with digitization/quantization differences as discussed in the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Ali
Ali 2016 年 1 月 23 日
編集済み: Ali 2016 年 1 月 23 日

0 投票

So, what is the fix? how can i have such a while loop with 0.1 increments and stop before 1?

4 件のコメント

Star Strider
Star Strider 2016 年 1 月 23 日
There is no fix, and even the most recent version of round (that my ‘roundn’ function emulates) will not produce an ‘exact’ decimal equivalent of a decimal fraction. Computers (most of them, at least) do everything in binary, and so have to express decimal fractions in binary approximations. (The only computer that I’m aware of that used decimal calculations was the IBM 1620 that I first learned FORTRAN on. The first several cards in a compiled deck loaded the lookup tables it used. IBM engineers called it the ‘CADET’ — Can’t Add, Doesn’t Even Try!)
roundn = @(x,n) round(x .* 10.^n)./10.^n; % Round ‘x’ To ‘n’ Digits, Emulates Latest ‘round’ Function
Run your code using format long E to see the reason b=0.1 is actually stopping before 1, just as you want it to:
format long E
a = 0;
b = 0.1;
c = a;
while c < 1
c
c = c+b;
end
Ali
Ali 2016 年 1 月 23 日
thank you
Star Strider
Star Strider 2016 年 1 月 23 日
My pleasure.
Image Analyst
Image Analyst 2016 年 1 月 23 日
"What's the fix?" Did you read the FAQ like both Star and I pointed you to? In there is the "fix" or way to deal with the reality of it -- you check against a tolerance.

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

カテゴリ

ヘルプ センター および File ExchangeIntroduction to Installation and Licensing についてさらに検索

質問済み:

Ali
2016 年 1 月 23 日

コメント済み:

2016 年 1 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by