I encounter a problem which I cannot understand.
a = 1.228269:0.000001:1.22828;
b = 1.228265:0.000001:1.22828;
ismember(a,b)
>> ismember(a,b)
ans =
1×12 logical array
0 1 0 1 1 1 1 1 1 1 1 1
It is clearly to see that the logical array is not compatible with the values in vectors a and b. An expert has suggested that this has to do with the floating point numerics, do anyone can explain what happened to this example and how to we circumvent it ? Thanks a lot !

 Réponse acceptée

Star Strider
Star Strider le 9 Déc 2016

3 votes

What happened is best explained in: Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero?
You can circumvent it using the ismembertol function (in R2015a and later versions).

4 commentaires

Qian Feng
Qian Feng le 9 Déc 2016
Modifié(e) : Qian Feng le 9 Déc 2016
It is not about ismember function in fact, I am using a and b for the index of a for loop. However, the results of the for loop between a and b is not matching. Note that the for loop should produce the same results for the overlapping values between a and b.
And Star's answer is not about ismember either. The problem is indeed one of floating point accuracy.
The number 0.000001 cannot be represented exactly in binary (the same way that you can't write 1/3 = 0.333... exactly in decimal), so every time you're adding 0.000001 you're accumulating some error (the same way if you did 0.333 + 0.333 + 0.333 = 0.999 in decimal). Because you're not starting at the same point (1.228269 vs 1.228265) the number at which the error accumulation is enough for it to matter differs for each sequence.
In your case, the simplest way to avoid this error accumulation is to multiply all your numbers by 1/0.000001 so you have integer boundaries and steps. All integers (up to flintmax) can be represented exactly as floating point, so you can't get any accumulation error. You can then do comparison on these integer values divided by 100000.
ia = 1228269:1228280
ib = 1228265:1228280
a = ia / 1e6;
b = ib / 1e6;
ismember(a, b)
Because the floating point value is obtained the same way for a and b (integer with no error / 1000000), the error is exactly the same for both numbers and they'll always compare equal for equal integers.
Qian Feng
Qian Feng le 17 Déc 2016
Thanks for the exposition here.
Star Strider
Star Strider le 17 Déc 2016
Our pleasure.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by