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일

1 개 추천

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

But when put 1.101 it till be false
n2 =
0.101000000000000
n2 =
0.010000000000000
n2 =
0.099999999999998
n2 =
0.999999999999979
n2 =
0.999999999999787
n2 =
0.999999999997868
...
Birdman
Birdman 2018년 1월 8일
I edited my answer.
Stephen23
Stephen23 2018년 1월 8일
편집: Stephen23 2018년 1월 8일
"This situation happens due to the fact that mod(1,1) is not actually zero, it is really close to zero"
Really?
>> mod(1,1)==0
ans = 1
Birdman
Birdman 2018년 1월 8일
편집: Birdman 2018년 1월 8일
Actually the derived 1 from calculation. I forgot to mention that.
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개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

질문:

2018년 1월 8일

편집:

2018년 1월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by