How to determine how a loop finishes
Mostra commenti meno recenti
Alright, so I have an assignment where I am to use the secant method to find the root of a function. I have the program written for the most part, and I'm able to find the root of a function no problem. However, I don't know how to have an output that can determine whether the loop finished because an answer was found, or if all the iterations were used and an answer was not located. I think I'm supposed to use an if/end or if/else kind of statement, but I'm not completely sure. I have the code listed below, any help would be greatly appreciated.
syms x
func=('x^2 - 4');
A=0; % A= x(k-1)
B=10;% B= x(k)
abs_err=0.00001;
n=5; %number of iterations
f = inline(func);
C = B - ((B-A)/(f(B) - f(A)))*f(B); % C= x(k+1)
display([' The function to be used is ' func])
fprintf(' The first guess, x(1) is equal to %g\n',A)
fprintf(' The second guess, x(2) is equal to %g\n',B)
fprintf(' The absolute approximate error, Ea, is equal to %g\n',abs_err)
fprintf(' The maximum number of iterations to conduct, n, is equal to %g\n',n)
disp(' ')
while abs(f(C)) > abs_err
A=B;
B=C;
C= B - ((B-A)/(f(B) - f(A)))*f(B);
n=n+1;
if(n==1000)
break
end
end
disp('Outputs')
display([' The root of the function = ' num2str(C)])
Risposta accettata
Più risposte (1)
Chris
il 18 Nov 2013
0 voti
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!