1

OS: Win 7 64bit. Matlab: 2014a, 2015a

When I create a vector as follows:

a = 0.2:0.2:1

I get:

a = 0.2000    0.4000    0.6000    0.8000    1.0000

which is expected. Now when I want to see whether 0.6 exists in my vector I type:

a == 0.6

and I get: 0 0 0 0 0

find(a == 0.6) also return an Empty matrix: 1-by-0

These are unexpected. It is able to find all the other values, but for 0.6 there is a problem. I think although 0.6 is created it is actually 0.600000000000000001 or something similar, which is a problem. You can see that this is the case by a > 0.6 and will get 0 0 1 1 1.

1-First of all why is this happening?

2-Second are we able to see the whole value of a number in Matlab, if so what is the function or setting for that?

I created the same vector using linspace, but that also did not help. I have found a solution to this by typing : a = roundn(a, -10). However, I think that such a solution should not even be needed at the first place.

3-Is there a better way to order Matlab to yield exact values?

Thank you all for your help.

4

1 に答える 1

3

まず、浮動小数点の値に関する MATLAB ドキュメントを読み、浮動小数点の誤差と精度に関するセクションに特に注意してください: MATLAB Floating Point

浮動小数点の精度に関して非常に一般的な問題が発生しています。実際には比較していないことを認識することが重要です。

>> a = 0.6;
>> b = 0.6;
>> a == b
   ans = 1

代わりに、効果的に比較しています:

>> a = 0.6;
>> b = 0.2 + 0.2 + 0.2;
>> a == b
   ans = 0

ここで明らかな論理的誤謬の理由は、算術が実際には等しくないからです。値0.60.2は両方とも、可能な値に最も近い倍精度浮動小数点で表されます。この違いは、「浮動小数点エラー」として知られています。

エラーの観察は簡単です。

>> a = 0.6;
>> b = 0.2 + 0.2 + 0.2;
>> a - b
   ans = -1.110223024625157e-16

最も簡単な解決策はround()、スカラーとベクトルを同じ精度で使用してから、比較を実行することです。

>> a = 0.6;
>> b = [ 0.2 : 0.2 : 1 ];
>> roundn ( a , -10) == roundn ( b , -10 )
   ans = 0 0 1 0 0
于 2015-04-26T19:31:32.417 に答える