%Bisection method%Step 1: Choose lower xl and upper xu guesses for%the root such that the function changes sign%over the interval. This can be checked by ensuring%that f(xl)*f(xu) < 0.%Step 2: An estimate of the root xr is determined%by xr = (xl + xu)/2%Step 3: Make the following evaluations to determine%in which subinterval the root lies:%(a) If f(xl)f(xr) < 0, the root lies in the lower%subinterval. Therefore, set xu 5 xr and return to step 2.%(b) If f(xl)f(xr) > 0, the root lies in the upper%subinterval. Therefore, set xl 5 xr and return to step 2.%(c) If f(xl)f(xr) = 0, the root equals xr; terminate the computation.%Example
func=@(m) sqrt(9.81*m/0.25)*tanh(sqrt(9.81*0.25/m)*4)-36;
% bisect: root location zeroes% input:% fm = name of function% xl, xu = lower and upper guesses% es = desired relative error% maxit = maximum allowable iterations% output:% root = real root% fx = function value at root% ea = approximate relative error (%)% iter = number of iterations
xl=40;
xu=200;
test = func(xl)*func(xu);
if test>0,error('no sign change'),end
es=0.0001;
maxit=50;
iter = 0; xr = xl; ea = 100;
disp(' iter xl xu xr ea')
while (1)
xrold = xr;
xr = (xl + xu)/2;
iter = iter + 1;
if xr ~= 0,ea = abs((xr - xrold)/xr) * 100;end
test = func(xl)*func(xr);
if test < 0
xu = xr;
elseif test > 0
xl = xr;
else
ea = 0;
end
fprintf('%3i %11.6f%11.6f%11.6f%11.6f\n',iter,xl,xu,xr,ea)
if ea <= es | iter >= maxit,break,endend
root = xr;
fx = func(xr);
mp = linspace(40,200);
fp = arrayfun(func,mp,'UniformOutput',false); %func(mp);
fp = cat(1, fp{:});
hold on
plot(mp,fp),grid
plot(root,fx,'.','MarkerSize',20)
hold off
No hay comentarios:
Los comentarios nuevos no están permitidos.