Rem function yields wrong output.

1 次查看(过去 30 天)
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?

采纳的回答

Honglei Chen
Honglei Chen 2017-10-23
编辑:Honglei Chen 2017-10-23
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 个评论
BM
BM 2017-10-24
Thanks, makes sense. I'll be careful about this in the future.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by