Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB ismember() problem

The following command returns 1:

ismember(-0.6, -1:.1:.9)

but this next command returns 0:

ismember(-0.1, -1:.1:.9)

even though -0.1 clearly is in -1:.1:.9.

Does anybody know what's going on?

like image 505
SamH Avatar asked Mar 18 '26 09:03

SamH


2 Answers

The problem is that when you start at -1.0 and add 0.1 repeatedly you get a slightly different number than if you specify -0.1 directly. This is because of floating-point error accumulation. Just like 1/3 cannot be represented exactly in decimal (it becomes 0.33333...), many decimal numbers cannot be represented exactly in binary. 0.1 when converted to binary is actually a very close approximation to 0.1. Because there is a slight error when you do arithmetic with this floating point number this small difference accumulates and becomes bigger and bigger.

From http://www.mathworks.com/matlabcentral/newsreader/view_thread/246492:

Ashwini Deshpande wrote:


I have a matrix as follows,

a = 0:0.1:1;

when I tried to find whether 0.300 is present in the matrix a, using the following procedure,

>> [tf, loc]=ismember(0.3,a)

I got the following result:

tf =
     0
loc =
     0

But it's suppose to give me, tf = 1 and loc =4.


You're getting the correct result, actually. Look what happens:

     v=0:.1:1;
     n=0.3;
     sprintf('%30.20f\n',v(4),n)
%{
     0.30000000000000004000 % <- result from vec
     0.29999999999999999000 % <- result from handwritten number
%}
     format hex;
     [v(4),n,v(4)-n].'
%{
     3fd3333333333334 % <- vec
     3fd3333333333333 % <- num
     3c90000000000000 % <- diff
%}
     format;

Also, peruse http://matlabwiki.mathworks.com/MATLAB_FAQ#Why_is_0.3-0.2-0.1_not_equal_to_zero_.28or_similar.29.3F

like image 89
John Kugelman Avatar answered Mar 21 '26 08:03

John Kugelman


Floating point error.

The number 0.1 is REALLY REALLY CLOSE to the value in the vector, but not exactly. Some numbers can not be represented exactly in a binary computer.

What are you trying to do exactly, there are many thresholding techniques that can work here if we know your situation better.

like image 32
MatlabDoug Avatar answered Mar 21 '26 08:03

MatlabDoug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!