as3rdaccount
as3rdaccount

Reputation: 3941

Not operator in Matlab behaving strangely

In my code I need to check if pairs of the differences between two consecutive members of a vector are equal/not equal and then do some stuff accordingly. Now here is a strange thing happening in Matlab say if I have a two pairs of two consecutive numbers so when I use

(x(i+3) - x(i+2)) ~= (x(i+1)-x(i)) 

it gives me a 1 even if both sides are equal. I think the reason is there is some round off error but not quite sure. For example,

x = [0,0.16,0.32,0.48,0.64,0.80];
>>a = x(5) - x(4)

a =

 0.1600

>>b = x(4) - x(3)

b =

 0.1600

>>a-b

ans =

5.5511e-17

Any idea how to get rid of this problem? Is there any different strategy to bypass ~= or == operators for this ind of problems?

Thanks in advance guys.

Upvotes: 2

Views: 94

Answers (1)

anon
anon

Reputation:

You should not compare floating-point numbers for equality that way. A more reliable way is to use abs(a-b)<eps if you are testing for equality.

Upvotes: 5

Related Questions