Borrar filtros
Borrar filtros

Is this a bug in max(x)?

1 visualización (últimos 30 días)
Ulrik William Nash
Ulrik William Nash el 8 de En. de 2018
Editada: Stephen23 el 8 de En. de 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 comentario
Guillaume
Guillaume el 8 de En. de 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);

Iniciar sesión para comentar.

Respuestas (1)

Stephen23
Stephen23 el 8 de En. de 2018
Editada: Stephen23 el 8 de En. de 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 comentarios
Steven Lord
Steven Lord el 8 de En. de 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.
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by