Rem function yields wrong output.

1 view (last 30 days)
BM
BM on 23 Oct 2017
Commented: BM on 24 Oct 2017
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?

Accepted Answer

Honglei Chen
Honglei Chen on 23 Oct 2017
Edited: Honglei Chen on 23 Oct 2017
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
  1 Comment
BM
BM on 24 Oct 2017
Thanks, makes sense. I'll be careful about this in the future.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!