Numerical Logical Statement Error
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2018-12-11
编辑:Stephen23
2018-12-11
"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
采纳的回答
James Tursa
2018-12-11
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.
更多回答(2 个)
madhan ravi
2018-12-11
编辑:madhan ravi
2018-12-11
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
>>
0 个评论
Steven Lord
2018-12-11
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!