Comparision double values 135 with 135.0000
1 view (last 30 days)
In my Matlab-Script there are two large vectors, I want to compare with each other at several indexes in a for loop. In one vector the value 135 is stored as the double-value "135" with a size of 8 Bytes. The other vector stores the same value, with the same size as "135.0000". A comparision with a simple if-statement and the == operator does not succeed.
What I did:
- using class() to verify the datatyp. Both are double
- parsing the two values to an integer with int64(). That doesnt make sense in my code
- using double() to force the same datatype. As documented by Mathworks, that has no effect: If X is already a double precision array, double has no effect.
How do I compare these two double-values?
What is the differnece between these two values, if they are both of the same datatype and the same size?
Stephen23 on 30 Nov 2021
Edited: Stephen23 on 30 Nov 2021
" A comparision with a simple if-statement and the == operator does not succeed."
Yes, it does succeed: their values are different, and so EQ correctly returns FALSE.
This is very easy to demonstrate:
X = pi
Y = pi+eps(pi)
X==Y % EQ operator "succeeds", because the values are NOT the same.
"How do I compare these two double-values?"
Using EQ compares the values for exact equivalence, which is not robust if you are working with binary floating point numbers. In that case the robust appraoch is to compare the absolute difference against a tolerance:
tol = 1e-5;
abs(X-Y)<tol % how to compare binary floating point numbers
"What is the differnece between these two values, if they are both of the same datatype and the same size?"
More Answers (1)
Awais Saeed on 30 Nov 2021
I had this issue once. I am just suggesting what helped me. It is possible that the actual value is not 135.0000. If 135.0000 is not comming out to be equal to 135, then it means that it is not equal after some decimal points.
The default format for display in matlab is format short. Use format long to see the difference. Here is an example below:
d1 = 135;
d2 = 135.0000000000001 % note what the result is. It just showed you the clipped version
isequal(d1,d2) % logic 0 would mean that two values are not equal
% Now use format long (this will show you the actual number)
What I did is to keep just 4 digits after the decimal, remove the rest, and then compare.