while loop until x amount correct digits

조회 수: 5 (최근 30일)
mohamed hassan
mohamed hassan 2020년 5월 7일
편집: Akihumi 2020년 5월 8일
Hi
Can someomene give me an example or an general way to write a while loop where the condition is that you need to have 3 correct decimals. ?
In my code I have a for loop but I need to make it more adapt.

채택된 답변

Akihumi
Akihumi 2020년 5월 7일
Have you considered using built-in function 'round'?
Then you can just do:
if round(x,3) == round(y,3)
...
end
  댓글 수: 11
Stephen23
Stephen23 2020년 5월 7일
Rounding is not the correct approach, read these to know why:
The correct way to is to compare the absolute difference against the required tolerance:
abs(A-B)<tol
Akihumi
Akihumi 2020년 5월 7일
편집: Akihumi 2020년 5월 8일
@Stephen Cobeldick thank you for the lesson.
Then it should be something like this i think
N = 0;
NLim = 1e10; % to stop the while loop if it goes too big
tol = 1e-5;
[r u] = main(N,a,k,Ta);
[r u2] = main(2*N,a,k,Ta);
disp(u(N+1))
disp(u2(2*N+1))
while N < NLim && abs(u(2*N+1)-u(N+1))>tol
N = N * 2;
u = u2;
[r u2] = main(2*N,a,k,Ta);
disp(u2(2*N+1))
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

mohamed hassan
mohamed hassan 2020년 5월 7일
Thanks for the help guys, I've done the question and got it correct.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by