0

I'm trying to compare three numbers in a if statement but they don't match even if they are the same.

here are the numbers from the command window,

>> a = (round2(final_aucscore(10, 1),1e-4))

a =

    0.9369

>> b = (round2(final_aucscore(10, 2),1e-4))

b =

    0.9598

>> c = (round2(final_aucscore(10, 3),1e-4))

c =

    0.9509

the function round2 can be found in the file echange here.

here's my code:

for mmm = 1:265

    a = (round2(final_aucscore(mmm, 1),1e-4));
    b = (round2(final_aucscore(mmm, 2),1e-4));
    c = (round2(final_aucscore(mmm, 3),1e-4));
    if   a == 0.9369 && b == 0.9598 && c == 0.9509
        auc_idx = idx(1:kk);
        save('auc_idx', 'auc_idx', 'mmm');
        break;
    end
end

shouldn't it stop and save when mmm = 10?

SamuelNLP
  • 4,038
  • 9
  • 59
  • 102
  • 1
    See: http://stackoverflow.com/questions/17877576/ – nkjt Jul 26 '13 at 21:53
  • 1
    That `round2` function on the FEX is terrible (and even has a 4.8 rating!). It's not even vectorized. *Such things should not be allowed.* It could be replaced by this anonymous function: `round2 = @(x,y)round(x./y).*y;` or you could edit the code. However, it's still going to be subject to the imprecision of floating-point. – horchler Jul 26 '13 at 22:05
  • [This function on the FEX](http://www.mathworks.com/matlabcentral/fileexchange/6077-round2), also called `round2`, appears to be much more numerically sound (only rated 4.3 though...). – horchler Jul 26 '13 at 22:13

2 Answers2

2

What every computer scientist should know about floating-point arithmetic. Read it and weep.

Marc Claesen
  • 16,778
  • 6
  • 27
  • 62
2

The problem you're facing here comes from rounding error. Try this

foo = 0.9369;
bar = (round2(foo,1e-4));
disp(bar == foo)
disp(foo-bar)

You could instead make a function to compare only within a certain precision.

horriblyUnpythonic
  • 853
  • 2
  • 14
  • 34