function bisect(f,a,b,tol,n)
% Bisection method for solving the nonlinear equation
f(x)=0.
a0=a; b0=b;
iter=0;
u=feval(f,a);
v=feval(f,b);
c=(a+b)*0.5;
err=abs(b-a)*0.5;
disp('_______________________________________________')
disp(' iter a b c f(c) |b-a|/2 ')
disp('_______________________________________________')
fprintf('\n')
if (u*v<=0)
while (err>tol)&(iter<=n)
w=feval(f,c);
fprintf('%2.0f %10.4f %10.4f %12.6f %10.6f %10.6f\n',
iter,a, b, c, w, err)
if (w*u<0)
b=c;v=w;
end;
if (w*u>0)
a=c;u=w;
end;
iter=iter+1;
c=(a+b)*0.5;
err=abs(b-a)*0.5;
end;
if (iter>n)
disp(' Method failed to converge')
end;
else
disp(' The method cannot be applied f(a)f(b)>0')
end;
% Plot f(x) in the interval [a,b].
fplot(f, [a0 b0])
xlabel('x'); ylabel('f(x)'); grid
function newton(f,df,x0,tol,n)
% Newton's method for solving the
nonlinear equation f(x)=0.
iter=0;
u=feval(f,x0);
v=feval(df,x0);
err=abs(u/v);
disp('__________________________________
____________')
disp(' iter x f(x) df(x) |xn+1-xn| ')
disp('__________________________________
____________')
fprintf('%2.0f %12.6f %12.6f %12.6f\n',
iter, x0, u, v)
while (err>tol)&(iter<=n)&(v~=0)
x1=x0-u/v;
err=abs(x1-x0);
x0=x1;
u=feval(f,x0);
v=feval(df,x0);
iter=iter+1;
fprintf('%2.0f %12.6f %12.6f %12.6f
%12.6f\n',iter,x0,u,v,err)
end
if (v==0)
disp(' division by zero')
end
if (iter>n)
disp(' Method failed to converge')
end
function falsep(f,a,b,tol,n )
% False position method for solving the
nonlinear equation f(x)=0.
a0=a; b0=b;
iter=0;
u=feval(f,a);
v=feval(f,b);
c=(v*a-u*b)/(v-u);
w=feval(f,c);
disp('__________________________________
____________________________')
disp(' iter a b
c f(c) |b-a| ')
disp('__________________________________
____________________________')
fprintf('\n')
if (u*v<=0)
while (abs(w)>tol)&(abs(b-
a)>tol)&(iter<=n)&((v-u)~=0)
w=feval(f,c);
fprintf('%2.0f %12.4f %12.4f %12.6f
%10.6f %10.6f\n', iter, a,b, c, w,
abs(b-a))
if (w*u<0)
b=c;v=w;
end;
if (w*u>0)
a=c;u=w;
end;
iter=iter+1;
c=(v*a-u*b)/(v-u);
end;
if (iter>n)
disp(' Method failed to converge')
end;
if (v-u==0)
disp(' Division by zero')
end;
else
disp(' The method cannot be applied
f(a)f(b)>0')
end;
fplot(f,[a0 b0])
xlabel('x');ylabel('f(x)'); grid