0

I have a 2D point vectorA and a rectangle with boundaries vectorX and vectorY. Following MWE represents my MATLAB code to check whether the point lies on the four consecutive boundaries:

vectorA=[1.6667 2];
vectorX=[0 1.6667];
vectorY=[2 3.3333]
if vectorA(1)==vectorX(1)
    disp('XL')
end
if vectorA(1)==vectorX(2)
    disp('XU')
end
if vectorA(2)==vectorY(1)
    disp('YL')
end
if vectorA(2)==vectorY(2)
    disp('YU')
end

I encountered a case for which the function did not detect that a given coordinate lied on a boundary. I printed the internal values of the variables and although I had if 1.6667==1.6667, that if was not evaluated.

Manually executing the consecutive calculations of my script works fine (including 1.6667==1.6667 which yields 1), but executing the script gives a wrong result. Where can I search for the reason for this strange behaviour?

Karlo
  • 1,630
  • 4
  • 33
  • 57
  • 2
    Probably an issue of floating point precision, take a look at this related question: http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab – Daniel Aug 22 '15 at 17:14

1 Answers1

1

The answer, most possibly, lies in the visual representation of numbers.

I mean that you see that the value is 1.6667 but the value (probably) is 1.666641239012783482983742987 (just random typing).

To play around with representations, check the format command. Start by typing in command window format long e and check again.

Xxxo
  • 1,784
  • 1
  • 15
  • 24
  • 1
    This might be suitable for some cases, but is no reliable method. For example `x=0.1+0.1+0.1; y=0.3; x==y` Both values look the same using the format, but they are not. I recommend to take the difference for debugging purposes instead. `x-y` – Daniel Aug 22 '15 at 17:16
  • Yeap... also a nice method for such cases! – Xxxo Aug 22 '15 at 17:27
  • 1
    This was indeed the problem. I replaced `if x==y` by `if abs(x-y) – Karlo Aug 22 '15 at 19:53