How to determine how a loop finishes
Afficher commentaires plus anciens
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)])
Réponse acceptée
Plus de réponses (1)
Chris
le 18 Nov 2013
0 votes
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!