Why doesn't .3 - .2 - .1 = 0

2 ビュー (過去 30 日間)
Lucas
Lucas 2012 年 11 月 9 日
I was bored yesterday at work and I was playing around with some decimal numbers when I stumbled across something I thought was pretty interesting.
.3 - .2 - .1 != 0
but
.2 - .1 - .1 = 0
then I began to run some other tests and I found out that only .3 and .8 are the only numbers that you use that'll not get you a 0 answer. If you take:
.4 - .2 - .1 - .1 = 0
and
.9 -.2 -.1 -.1 -.1 -.2 -.1 -.1 = 0
If you change any of the .2's to two - .1's you don't get 0. So what’s so special about those 2 decimals that make them the only ones that don't work with basic subtraction?

採用された回答

Matt J
Matt J 2012 年 11 月 9 日
編集済み: Matt J 2012 年 11 月 9 日
What makes them special? Nothing. There are lots more numbers like that
>> isequal(0, .7 - .5 - .2)
ans =
0
It also depends on the operation you do. Sometimes 0.3 will work fine, e.g.,
>> isequal(0, .6 - .3 -.3)
ans =
1
  2 件のコメント
Matt Fig
Matt Fig 2012 年 11 月 9 日
It is not just in MATLAB. ALL numerical systems that follow IEEE 754 will behave this way. That is the standard.
José-Luis
José-Luis 2012 年 11 月 9 日
編集済み: José-Luis 2012 年 11 月 9 日
This is not Matlab specific. It has to do with the fact that computers use binary numbers and humans tend to feel more comfortable with decimals. Things gets lost in translation and these are the side effects.

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

その他の回答 (1 件)

Thomas
Thomas 2012 年 11 月 9 日
編集済み: Thomas 2012 年 11 月 9 日
This should answer your question. Look at the wiki under the section Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero? (might have to scroll on the page to locate...)
  2 件のコメント
Dr. Seis
Dr. Seis 2012 年 11 月 9 日
編集済み: Dr. Seis 2012 年 11 月 9 日
I had similar issues when doing mod(0.4,0.4) and mod(0.8,0.4) returning a number slightly smaller than 0.4 instead of 0. Whenever I do these types of comparisons in the future I will need to overload the builtin functions.
Oleg Komarov
Oleg Komarov 2012 年 11 月 9 日
@Lucas, if you already know that you wouldn't be asking the question in the first place. I recommend to read the FAQ more carefully.

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

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by