Why is logical array fasle?
1 次查看(过去 30 天)
显示 更早的评论
SCRIPT WINDOW
g=9.8000 %value for g
p=3.14; %value of mathematical pie
k1=3.1210191*p
k1==g %generation of logical array
COMMAND WINDOW
g =
9.8000
k1 =
9.8000
ans =
logical
0![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/654025/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/654025/image.png)
0 个评论
回答(3 个)
Scott MacKenzie
2021-6-15
The result is false because k1 DOES NOT EQUAL g
Note that both k1 and g are scalars, not vectors. Therefore, the result of k1==g is a logical scalar which is false or 0.
0 个评论
Steven Lord
2021-6-15
Floating point arithmetic. While k1 and g are displayed the same they do not contain the same value down to the last bit.
0 个评论
Kunal Kandhari
2021-6-15
It is because most decimal fractions are not exactly representable in binary form, just like 1/3 is not representable exactly in a finite number of decimal digits.
if you print 55 decimal places of both the variables you will get something like this:
sprintf('%0.55f',k1)
'9.7999999740000003356499291840009391307830810546875000000'
sprintf('%0.55f',g)
'9.8000000000000007105427357601001858711242675781250000000'
NEVER compare two floating point doubles for exact equality. Well, there are some notable exceptions. So unless you know the exceptions, then assume never applies.
You can see a very detailed description of the same here:
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!