array element not equal to equivalent double

5 visualizaciones (últimos 30 días)
Pierre-Vincent
Pierre-Vincent el 15 de Nov. de 2022
Comentada: Pierre-Vincent el 15 de Nov. de 2022
I have the following code:
array=0.0001:0.0001:0.6;
x=0.0402
x = 0.0402
y=array(402)
y = 0.0402
test=x==y
test = logical
0
the result of the test is 0 and I really don't understand why... Both are supposed to be double. Can somebody help?
(the final idea is to find the index of X in the array with the find function)

Respuesta aceptada

Matt J
Matt J el 15 de Nov. de 2022
Editada: Matt J el 15 de Nov. de 2022
Because computers cannot do exact math. The difference between x and y beyond the 4th decimal place make this clear:
array=0.0001:0.0001:0.6;
x=0.0402
x = 0.0402
y=array(402)
y = 0.0402
x-y
ans = -6.9389e-18
  2 comentarios
Matt J
Matt J el 15 de Nov. de 2022
Editada: Matt J el 15 de Nov. de 2022
Instead, you can do,
array=0.0001:0.0001:0.6;
x=0.0402;
idx=interp1(array,1:numel(array),x,'nearest')
idx = 402
Pierre-Vincent
Pierre-Vincent el 15 de Nov. de 2022
thanks :)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by