Why does comparing identical doubles result in a logical 0?
26 views (last 30 days)
Show older comments
Hi there,
I have the problem that the comparison of doubles which I have exported from another software (COMSOL Multiphysics) with doubles of identical value result in a logical 0. How can I fix this? I've documented the problem above by copying the contents of my Command Window below:
==============
v =
1.0e+03 *
2.5000
2.0000
0.6000
>> v(2)
ans =
2.0000e+03
>> v(2)==2000
ans =
0
>> w=double(2000);
>> v(2)==w
ans =
0
>> whos v
Name Size Bytes Class Attributes
v 3x1 24 double
>> whos w
Name Size Bytes Class Attributes
w 1x1 8 double
>> v(2)==2.0000e+03
ans =
0
>>
==============
Any help would be highly appreciated.
Thanks a lot in advance, Joerg
0 Comments
Accepted Answer
Jan
on 19 Mar 2013
When you observe, that v(2)==2000, it is a straight idea to ask Matlab for the difference between these numbers:
v(2) - 2000
This is an effect of the limited number of digits in the output in the Command Window, and the limited precision of floating point values, see: http://www.mathworks.com/matlabcentral/answers/57444-faq-why-is-0-3-0-2-0-1-not-equal-to-zero
More Answers (2)
Wayne King
on 19 Mar 2013
Edited: Wayne King
on 19 Mar 2013
This is the well-known (and often treated in this forum) problem of floating-point precision. The point is that they are not identical.
You can use a tolerance to compare the numbers like abs(x-y)<lambda
where lambda is some very small number.
See the help for eps()
Shashank Prasanna
on 19 Mar 2013
Edited: Shashank Prasanna
on 19 Mar 2013
If you want to see how they are different, try:
>> format hex
>> v(2),2000
change display format back to default
>> format
0 Comments
See Also
Categories
Find more on Numeric Types 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!