while loop until x amount correct digits
20 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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
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
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 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!