martes, 22 de octubre de 2019

MATLAB code Bisection Method (root)



Raices_bisection
%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,end
end
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
iter       xl        xu        xr         ea
  1    120.000000 200.000000 120.000000  66.666667
  2    120.000000 160.000000 160.000000  25.000000
  3    140.000000 160.000000 140.000000  14.285714
  4    140.000000 150.000000 150.000000   6.666667
  5    140.000000 145.000000 145.000000   3.448276
  6    142.500000 145.000000 142.500000   1.754386
  7    142.500000 143.750000 143.750000   0.869565
  8    142.500000 143.125000 143.125000   0.436681
  9    142.500000 142.812500 142.812500   0.218818
 10    142.656250 142.812500 142.656250   0.109529
 11    142.734375 142.812500 142.734375   0.054735
 12    142.734375 142.773438 142.773438   0.027360
 13    142.734375 142.753906 142.753906   0.013682
 14    142.734375 142.744141 142.744141   0.006841
 15    142.734375 142.739258 142.739258   0.003421
 16    142.736816 142.739258 142.736816   0.001710
 17    142.736816 142.738037 142.738037   0.000855
 18    142.737427 142.738037 142.737427   0.000428
 19    142.737427 142.737732 142.737732   0.000214
 20    142.737579 142.737732 142.737579   0.000107
 21    142.737579 142.737656 142.737656   0.000053

No hay comentarios: