-1

While learning MATLAB, I came across a strange problem with my code. I am trying to receive a number as user input and determine whether the inputted number is in the desired range of 5.4±0.1. As you can see below, I took absolute value of the difference between input and 5.4 and checked if it is less than or equal to 0.1. By the code, any number between 5.3 and 5.5 should output "Part is good," but strangely, it doesn't work for the lower bound, 5.3. Every number between 5.3 and 5.5 works except for 5.3, and even 5.5 (the upper bound) works well. I am wondering if there is something with MATLAB that I am not aware of yet. Thank you!

part = input("Enter the length of a part"); %user input (height)
if (part<0) %if input is a negative number
   error("Illegal input"); %error message
elseif (abs(part-5.4) <= 0.1) %if input is 5.4+-0.1
   disp("Part is good"); %display 'part is good'
else % if not
   disp("Part is not good"); %display 'part is bad'
end

1 Answers1

0

First, none of the numbers you are dealing with except 5.5 can be represented exactly in IEEE double precision floating point binary. So you cannot rely on these edge cases to work out exactly as if they were represented exactly in floating point decimal because they aren't. To see this, here are the exact conversions of the underlying floating point binary bit patterns to decimal which show why one edge calculation works and the other doesn't. Bottom line is you need to use tolerances (e.g., something slightly bigger than 0.1) or do your calculations differently if you want your edge cases to work as expected in decimal. This isn't a MATLAB bug ... it is simply how floating point binary calculations work. Any language that uses IEEE floating point in the background will have the same issues that must be accounted for by the programmer when writing code.

enter image description here

A more detailed discussion can be found here: Why is 24.0000 not equal to 24.0000 in MATLAB?

James Tursa
  • 2,242
  • 8
  • 9