フィルターのクリア

Is this a bug in max(x)?

3 ビュー (過去 30 日間)
Ulrik William Nash
Ulrik William Nash 2018 年 1 月 8 日
編集済み: Stephen23 2018 年 1 月 8 日
I have the following two vectors:
a = [0.5 0.6 0.1 0.2 0.2]; b = [0.5 0.4 0.1 0.0 0.0];
and I now define x as their difference:
x = a - b,
which yields
x = [0 0.2 0 0.2 0.2].
You will notice there are 3 maximum values.
But, [~,I] = max(x) insists on calculating I = 4.
Why?
  1 件のコメント
Guillaume
Guillaume 2018 年 1 月 8 日
Note that for vectors, I is always scalar (index of the occurence) regardless of how many times the maximum occur. If you want the index of all instances:
I = find(abs(x - max(x)) <= tol);

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

回答 (1 件)

Stephen23
Stephen23 2018 年 1 月 8 日
編集済み: Stephen23 2018 年 1 月 8 日
"Is this a bug in max(x)?"
There is no error with MAX. Floating point numbers cannot exactly represent those values, and you forgot to take that into account in your calculation. Lets have a look at those values at a higher precision:
>> fprintf('%.30f\n',x)
0.000000000000000000000000000000
0.199999999999999955591079014994
0.000000000000000000000000000000
0.200000000000000011102230246252
0.200000000000000011102230246252
MAX is completely correct.
  6 件のコメント
Steven Lord
Steven Lord 2018 年 1 月 8 日
Do this experiment for me, please. Find something on which to write and something with which to write. A piece of paper and a pencil, or a whiteboard and a marker, or a sandbox and a stick, would each work.
Using long division, compute x = 1/3 to as many decimal places as you want (though the only symbols you're allowed to use are the digits 0 through 9 and one decimal point. No "x = 0.3 repeating"; you have to write out as many decimal places as you want.) Now multiply 3*x.
In theory, 3*x should be exactly 1. In practice, because of round-off error in how you computed x, it will be slightly less than one third and so 3*x will be slightly less than 1.
In decimal, you can't exactly represent one third. x = 1/3 is "something different, albeit close". In decimal you can exactly represent two tenths as 0.2. In IEEE double precision, you can't represent either one third or two tenths exactly.
See this Answer and this Answer for more information. I particularly recommend the Cleve's Corner articles linked in each as well as Goldberg's paper "What Every Computer Scientist Should Know About Floating Point Arithmetic" linked in the second.
Stephen23
Stephen23 2018 年 1 月 8 日
編集済み: Stephen23 2018 年 1 月 8 日

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

カテゴリ

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