# Is this a bug in max(x)?

2 Ansichten (letzte 30 Tage)
Ulrik William Nash am 8 Jan. 2018
Bearbeitet: Stephen23 am 8 Jan. 2018
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 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Guillaume am 8 Jan. 2018
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);

Melden Sie sich an, um zu kommentieren.

### Antworten (1)

Stephen23 am 8 Jan. 2018
Bearbeitet: Stephen23 am 8 Jan. 2018
"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 Kommentare4 ältere Kommentare anzeigen4 ältere Kommentare ausblenden
Steven Lord am 8 Jan. 2018
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.
Stephen23 am 8 Jan. 2018
Bearbeitet: Stephen23 am 8 Jan. 2018

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Logical finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by