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.
0 个评论
采纳的回答
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
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
2018-1-8
Yes, exactly. Sorry for misinformation. I meant the value obtained by this calculation is not equal to 1.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!