Numerical Logical Statement Error

1 view (last 30 days)
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 Comment
Stephen23
Stephen23 on 11 Dec 2018
Edited: Stephen23 on 11 Dec 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

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 11 Dec 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.

More Answers (2)

madhan ravi
madhan ravi on 11 Dec 2018
Edited: madhan ravi on 11 Dec 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 on 11 Dec 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.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!