Numerical Logical Statement Error

13 Ansichten (letzte 30 Tage)
Limanan Nursalim
Limanan Nursalim am 11 Dez. 2018
Kommentiert: Limanan Nursalim am 11 Dez. 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 Kommentar
Stephen23
Stephen23 am 11 Dez. 2018
Bearbeitet: Stephen23 am 11 Dez. 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

James Tursa
James Tursa am 11 Dez. 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.

Weitere Antworten (2)

madhan ravi
madhan ravi am 11 Dez. 2018
Bearbeitet: madhan ravi am 11 Dez. 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 am 11 Dez. 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.

Community Treasure Hunt

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

Start Hunting!

Translated by