Effacer les filtres
Effacer les filtres

Minute error in array causes == to be ineffective

2 vues (au cours des 30 derniers jours)
random09983492 le 26 Juil 2012
Hi, I am trying to use an if statement using the == comparator to search an array of numbers. Something like this:
for i = 1:100
if a == array(i,1)
% do stuff here
Doing this, however, leads to the if statement never being true. When I would expect a and the array value to be equal, the statement is still false, due to a very minute difference of something around the order of 10^-8.
What is causing this very small error and what are some of the workarounds you guys suggest? Alternatively, is there a smarter way to search an array of numbers?

Réponse acceptée

Wayne King
Wayne King le 26 Juil 2012
Modifié(e) : Wayne King le 26 Juil 2012
Hi Elliot, this is a reality of dealing with floating point numbers. You could use a tolerance
a = randn(10,1);
for ii = 1:length(a)
if (abs(a(ii)-0)<1e-6)
For example
x = 1+1e-7;
y = 1.000000;
They look the same, but
returns a 1 (true)

Plus de réponses (1)

Walter Roberson
Walter Roberson le 26 Juil 2012


En savoir plus sur Logical dans Help Center et File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by