MATLAB Answers

Floating point numeric problem

15 views (last 30 days)
Qian Feng
Qian Feng on 9 Dec 2016
Commented: Star Strider on 17 Dec 2016
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)
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 !


Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 9 Dec 2016
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).


Show 1 older comment
Guillaume on 9 Dec 2016
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 on 17 Dec 2016
Thanks for the exposition here.

Sign in to comment.

More Answers (0)