There something wrong about mod function

3 次查看(过去 30 天)
This is my script function code:
function test(n)
n2=mod(n,1)
while (n2) ~= 0
n2 = mod((n2)*10,1);
end
n2;
I try to do this:(example) I put 0.101 into and need the output like n2 = 0.101; n2 = 0.01; n2= 0.1; n2 =0; but there something wrong, because the output of the above code like this:
n2 =
0.101000000000000
n2 =
0.010000000000000
n2 =
0.100000000000000
n2 =
8.881784197001252e-16
n2 =
8.881784197001252e-15
n2 =
8.881784197001252e-14
n2 =
8.881784197001252e-13
and so on to
n2 =
0.250000000000000
n2 =
0.500000000000000
n2 =
0
So, I don't know why it like this.

采纳的回答

Birdman
Birdman 2018-1-8
编辑:Birdman 2018-1-8
This situation happens due to the fact that
mod(1,1)
is not actually zero, it is really close to zero. You need to indicate a condition whether the value is under a certain tolerance or not. Change your code to the following:
function test(n)
n2=mod(n,1)
while (n2) ~= 0
if ismembertol(n2,fix(n),1e-5) || n2<1e-5
break;
else
n2 = mod((n2)*10,1);
end
end
n2;
With the above if condition, we assume the number n2 as zero if it is smaller than 1e-5.
For further information, please refer to the following link:
  6 个评论
Stephen23
Stephen23 2018-1-8
编辑:Stephen23 2018-1-8
@Birdman: a 1 derived from a calculation would still be a 1. Your wording could be improved to correctly point out that the value obtained by this calculation is not equal to 1. Currently your answer implies that 1 is not equal to 1, which is incorrect and misleading.
Birdman
Birdman 2018-1-8
Yes, exactly. Sorry for misinformation. I meant the value obtained by this calculation is not equal to 1.

请先登录,再进行评论。

更多回答(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