There something wrong about mod function
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Birdman
on 8 Jan 2018
Edited: Birdman
on 8 Jan 2018
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 Comments
Stephen23
on 8 Jan 2018
Edited: Stephen23
on 8 Jan 2018
@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
on 8 Jan 2018
Yes, exactly. Sorry for misinformation. I meant the value obtained by this calculation is not equal to 1.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!