I am trying to compare an array of doubles to a scalar double for equality, but equality is never recognized under certain circumstances. I suspect that this has to do with the way the double is represented (e.g., 1.0 vs 1.00), but I can't figure it out.
For instance, I have generated an array composed of thousands of double values, the last few of which at some instant in time are given by
10.6000
-11.0000
10.2000
22.6000
3.4000
If I test for equality to 10.2 (or 10.2000) by the command array==10.2
(or array=10.2000
), I return an array of 0s. If I place the values shown into an array manually (e.g., array=[10.6000 -11.0000 10.2000 22.6000 3.4000]
), then the command is successful (i.e., array==10.2
returns 0 0 1 0 0
). Could someone please explain why the equality succeeds if I input the values manually, but fails if the array is generated in the context of a program? I am able to rectify the comparison failure by using an approximate rather than an exact comparison (e.g., (array<10.20001) & (array>10.19999)
), but this seems unsatisfying.
Edit: The values in the array are generated by iterative addition or subtraction of a constant double (e.g., 0.2
). The modulus of this array by 0.2
should therefore be everywhere equal to 0
. In fact, the modulus of each element is equal to either 0
or 0.2
, as shown below for the above sequence of numbers in the array:
mod(array,0.2)
...
0.2000
0
0.2000
0.2000
0
Again, if the values are placed in an array manually and the modulus is taken, the expected value of all 0
s is obtained.
The reason is MATLAB truncated the numbers in the array to preserve only 4 digits after the decimal point when displaying,. That is, the real value of your array may be [10.600000000001, -10.99999999999, ...]
. You are right, this is due to the internal representation of floating-point numbers in computer, which may cause tiny errors in the computations.
Personally I think there are two solutions, one is approximate matching like you did, while the other is to round the array up first (say, with this tool from FileExchange), and then do exact matching.
Something is probably in single precision somewhere, and double elsewhere. The binary representation of e.g. 10.2 in each is different as they terminate after a different number of bits. Thus they are different:
>> if (single(10.2) == 10.2) disp('honk'); end
>> if (single(10.2) == single(10.2)) disp('honk'); end
honk
You'll need to check for equality within some small difference:
eps = 0.001;
result = abs(array-10.2) < eps;
You can find the precision used in an array using whos:
>> whos A
Name Size Bytes Class Attributes
A 1x2 8 single
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With