Numerical Logical Statement Error

1 visualización (últimos 30 días)
Limanan Nursalim
Limanan Nursalim el 11 de Dic. de 2018
Comentada: Limanan Nursalim el 11 de Dic. de 2018
Can anyone explain me what's actually happening? Why is the result true, although they are obviously not? How do I fix this problem?
K>>Us
Us =
-1.7280e+03
K>> P(ct).L
ans =
-1.7268e+03
K>> err
err =
1.0000e-03
K>> (Us-P(ct).L) <= err
ans =
logical
1
  1 comentario
Stephen23
Stephen23 el 11 de Dic. de 2018
Editada: Stephen23 el 11 de Dic. de 2018
"Can anyone explain me what's actually happening?"
Sure, lets just take a look at the value:
>> -1.7280e+03 - -1.7268e+03
ans = -1.2000
Is -1.2 less than 1? Yes, it is (all negative values are less than 1).
"How do I fix this problem?"
The standard way is to use abs:
>> abs(-1.7280e+03 - -1.7268e+03) < =1
ans = 0

Iniciar sesión para comentar.

Respuesta aceptada

James Tursa
James Tursa el 11 de Dic. de 2018
Both of your numbers are negative, so I don't think this test does what you intended. E.g.,
>> ct = 1;
>> Us = -1.7280e+03
Us =
-1728
>> P(ct).L = -1.7268e+03
P =
struct with fields:
L: -1.7268e+03
>> err = 1.0000e-03
err =
1.0000e-03
>> Us-P(ct).L
ans =
-1.2000
>> (Us-P(ct).L) <= err
ans =
logical
1
You probably want an abs( ) wrapper:
>> abs(Us-P(ct).L) <= err
ans =
logical
0
And, if the values are very close to the err, note that floating point calculations might not give you the result you expected either, so you may need a tolerance on the tests.

Más respuestas (2)

madhan ravi
madhan ravi el 11 de Dic. de 2018
Editada: madhan ravi el 11 de Dic. de 2018
Just search with a tag floating-point and you will find lots explanations dealing with floating numbers , but obviously Us is lesser than the other.
>> vpa(-1.7280e+03)
ans =
-1728.0
>> vpa(1.0000e-03) % obviously it's positive
ans =
0.001
>>

Steven Lord
Steven Lord el 11 de Dic. de 2018
Display the quantity (Us-P(ct).L). It is indeed smaller than err.
Now the absolute value of (Us-P(ct).L) is not smaller than err, but that's not what you asked MATLAB to compute.

Categorías

Más información sobre Matrices and Arrays 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