I need to find the roots of a function by creating a function that uses the secant method. The outputs are all stated below and explained, for some reason my loop is never ending

3 vues (au cours des 30 derniers jours)
function [ root,err,numIter, exitFlag ] = secant( fun, prev, curr, err_max, iter_max )
%check to see if the end points are roots
%inputs: fun = function that is being used to find the roots
% prev = intial lower bound
% curr = initial upper bound
% err_max = max acceptable relative approximation error
% iter_max = number of iterations taken
%
%outputs: root = root location
% err = relative error of solution
% numIter = number of iterations used
% exitFlag = termination status
%
%exit flag encoding: 1 : algorithm terminated normally (due to error being sufficiently small)
% 0 : algorithm terminated due to max iterations being reached
% -1 : algorithm terminated due to invalid bracket specification (no root in bracket)
% -2 : algorithm terminated due to invalid return value from function fun (e.g., NaN, Inf,
% empty bracket)
numIter = 1;
err = ((curr-prev)/(curr+prev))*100;
x(1) = prev;
x(2) = curr;
while i <= iter_max
i = i +1
x(i+1) = x(i) - (fun(x(i)))*(x(i)-x(i-1))/(fun(x(i))-fun(x(i-1)));
err = abs((x(i)-x(i+1))/(x(i)*100));
if isnan(x(i+1)) == 1
x(i+1)=x(i);
break
end
%%here it checks that the max error hasn't been met so it can move on to the next iteration
if err < err_max
root = x(i);
exitFlag = 1;
end
if i == iter_max
exitFlag = 0;
disp('Max iterations were reached')
break
end
x(i-1) = x(i);
x(i) = x(i+1);
end
root = x(i+1);
end

Réponses (1)

Walter Roberson
Walter Roberson le 7 Oct 2016
Your test if err < err_max does not have a "break".
Your test if i == iter_max is not necessary, since you have while i <= iter_max
Your test if isnan(x(i+1)) == 1 does not set the exit flag.

Catégories

En savoir plus sur Language Fundamentals dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by