MATLAB: Rem function yields wrong output.

errorinconsistentmodremresult not expected

I am assuming that there is a little error (perhaps floating point), in my test loop. This particular loop I wrote is supposed to ensure that I have integer numbers. For example:
a = 0.07;
T = 150;
Value = 2*a*T
if rem(2*a*T,1) ~= 0
error('2*p*stripsteps must be an integer value.')
end
Result = 2*a*T
which yields:
untitled
Value =
21.0000
Error using untitled (line 9)
2*p*stripsteps must be an integer value.
As one can see, Result does not print, but it should! Value and Result should both print and give me the same value, as they are both the same integer. When I use the rem function; however, I get the value:
rem(2*a*T,1)
ans =
3.5527e-15
But, if I plug in the actual value of 2*a*T, which is 21, as one can see from the initial section of code, I get the correct value:
rem(21,1)
ans =
0
Does anyone have any suggestions on how I can address this issue?

Best Answer

This is due to the round off error from floating point computation. The following link might be helpful
In general you can try to use a tolerance, for example, instead of using
if rem(2*a*T,1)~=0
Use
temp = 2*a*T;
if abs(round(temp)-temp)>sqrt(eps)
HTH
Related Question