Help with iteration counter not working or displaying wrong numbers?
7 ビュー (過去 30 日間)
古いコメントを表示
Ralph Rodrigues
2021 年 2 月 25 日
コメント済み: Ralph Rodrigues
2021 年 2 月 26 日
Hi, I was creating some code to solve an equation using bisection and regula falsi. I wanted to see which method converges faster so I decided to make an iteration counter to count how many iterations were done for each result to meet my tolerance value (0.001). I'm not sure why the iterations number which are displayed along side my other value are the same for both methods. They also have decimal places. Is there somewhere in bisect.m or regfalsi.m where I am making a mistake or in main.m where I pull the iteration values in part B and C.
Specifically this area
function bisectioncalc = bisect(f,a,b) %Head is the num.soln
c = (a+b)/2; % calculation of midpoint
r = abs(f(c));
I=0;
while r > 0.001
if (f(a)*f(c))<0
b = c; % c values becomes a
elseif (f(b)*f(c))<0
a = c; % c values becomes b
end
c = (a+b)/2;
r = abs(f(c)); %relative error/tolerance formula
I = I + 1;
end
bisectioncalc = c; %assign c back to bisectionfalsicalc
end
I want to know whether my placment of the counter is correct and if I am calling it correctly in main.m
Thank you!
3 件のコメント
採用された回答
Walter Roberson
2021 年 2 月 25 日
f = @(H) v -((sqrt(19.62.*H)*tanh(sqrt(19.62.*H)*t/(8))));
%Head = fzero(f,b); % find root using fzero()
H = bisect(f,a,b);
I = bisect(f,a,b);
Why are you calling the same bisect() twice? Is it non-deterministic? You are not timing it, so it is not for the purposes of getting more accurate timing.
5 件のコメント
Walter Roberson
2021 年 2 月 26 日
No, it was because you never tried to return I from the function.
The syntax
function [bisectioncalc, I] = bisect(f,a,b) %Head is the num.soln
does not have anything to do with arrays. The [] on the left is just syntax that does not really have to do with using [] for constructing arrays. MATLAB could have designed it as, for example,
function #bisectioncalc, #I = bisect(f,a,b) %Head is the num.soln
to invent a syntax.
その他の回答 (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!