0

I just can't figure it out why 'a' and 'b' are different. (Of course precesion problem with floating points but are they not equally off?)

a = 1 - 2 + 2e-13;
b = 1 + 2e-13 - 2;
isequal(a,b)
d = a-b

ans = 0
d = -1.110223024625157e-16

lnksz
  • 421
  • 3
  • 15
  • 1
    Lesson learned - **NEVER** use equality to compare floating point numbers. The operation may look the same, but the sequence of operations that lead you to the final answer in terms of the CPU operations are different. This is the main reason why equality usually fails. If you want to compare floating point numbers, compare them within some small tolerance. Please read the following canonical website for more details: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html - Also take a look at the duplicate question that has been marked. Good luck! – rayryeng Apr 20 '16 at 20:32
  • Yeah, it is not a real life use-case, just wondering why ìt influenced by the order, Regard this: `>> a = - 2 + 2e-13; >> b = 2e-13 - 2; >> isequal(a,b)` Gives 1 as result. So could it be the +1 which raises the value over a limit, where the precision is not sufficient? – lnksz Apr 25 '16 at 07:08
  • Try doing `format long g;` and display the operations. Sometimes the values may equal... sometimes it won't. It totally depends on your CPU, OS, programming language, etc. In any case, never rely on equality ever. Compare floating point values within a certain tolerance. – rayryeng Apr 25 '16 at 07:24

0 Answers0