There something wrong about mod function
2 ビュー (過去 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!