3

I'm trying to test the value of an iteration variable in a for loop and I'm not getting what I expect so I'm assuming that I'm misunderstanding something about the way matlab works and/or I'm doing something horribly wrong....

Can someone explain why the if statement in this code doesn't test true when x hits 0.2?:

start = -1;
stop = 1;
interval = 0.01;

for x = start:interval:stop
    if x == 0.20
        disp('it worked')
    end
end

But this code does test true:

start = 0;
stop = 1;
interval = 0.01;

for x = start:interval:stop
    if x == 0.20
        disp('it worked')
    end
end

I tried a bunch of different starting values and they seem to be random as to whether they work or not....Why should changing the starting value change the output?

I also see a similar inconsistency if I change the tested value (ie. 0.2 to 0.8 or something else)

What am I missing?

Jonathan
  • 1,205
  • 1
  • 10
  • 12
  • Wow this is very interesting. From a preliminary inspection if you form `x = -1:0.01:1.` Then you do `x(121) - 0.2` you basically get a very small number close to machine precision. If you define `c` as `c = x(121)-0.2` then input `x(121) == 0.2+c` the answer is true, and as mentioned before `c` is close to machine precision. – JustinBlaber Mar 20 '13 at 03:11

1 Answers1

4

You are testing a floating point number with ==. Note that -1+120*.01==0.2 is false since they are not equal in the floating point representation. 0.01*20==0.2 happens to be true. Instead, use a tolerance e.g. if abs(x-0.20)<1e-10.

Ramashalanka
  • 8,564
  • 1
  • 35
  • 46
  • 1
    @Jonathan: Useful links are http://stackoverflow.com/questions/10334688/how-dangerous-is-it-to-compare-floating-point-values and http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html and (thanks @jucestain) http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm. – Ramashalanka Mar 20 '13 at 03:18
  • Deleted my comment because the first sentence says the article is obsolete. This is very interesting stuff though. I read about how floating point numbers are constructed a while ago but to see the implications of this directly are still surprising. – JustinBlaber Mar 20 '13 at 03:27
  • @jucestain: yes, here is the updated version: http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/. There are lots of other interesting articles on that site. – Ramashalanka Mar 20 '13 at 03:36
  • ugh, if only I had remembered floating point precision before I spent an hour trying to figure out what was going on! Thank you for refreshing my memory!! – Jonathan Mar 20 '13 at 03:45