MATLAB is giving a false result to a condition that is

3 visualizaciones (últimos 30 días)
Dioner Rondon
Dioner Rondon el 9 de Mzo. de 2017
Editada: KSSV el 9 de Mzo. de 2017
Hello.
I have encountered a problem while programming a little script.
The problem is I am evaluating two variables are the same within an 'if'.
Looks like MATLAB thinks they are not the same, when they obviously are, thus generating error in my program. This is what happens:
if dif == dq
a=1
else
a=0
end
a =
0
When I ask matlab the values of dif and dq
>> dif
dif =
0.0500
>> dq
dq =
0.0500
I realised this happens when the values of dq, and dif, are generated from my program, dif is the result of the absolute value of the difference between two values of a vector, and dq is just a difference divided by two.
If I manually assign the values of dif and dq, an then evaluate dif==dq, I do get a 1.
When the program fixes the values, and even when they are the same, I evaluate dif==dq and it returns me 0.
I'm sure must be something very simple that I am not seeing, I still don't know where I'm wrong. Certainly I am new at using the MATLAB software.
Any help would be appreciated, thanks!

Respuesta aceptada

KSSV
KSSV el 9 de Mzo. de 2017
Editada: KSSV el 9 de Mzo. de 2017
You should not compare floating point numbers like that. Better, you calculate the difference and check for absolute of difference to be less then certain very small parameter. This is suggested to compare floating point numbers.
eps = 10^-6 ; % a small parameter
if abs(dif-dq)<=eps
a=1
else
a=0
end

Más respuestas (0)

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by