Section
2.3
1. Newton’s Method
function [ iter ] = mynewton1(f, df,x0, tol,n)
%UNTITLED3 Summary of this function goes here--please write
% Detailed explanation goes here -please write
%
%
%
%
iter=0;
u=feval(f, x0);
%evaluate function f at x0
v=feval(df,x0);
err=abs(u/v);
% err can be set up differently. for example 1.
disp('-------------------------------------------')
disp('iter x f(x) |xn+1-xn| ')
disp('-------------------------------------------')
fprintf('%2.0f %12.6f %12.6f %12.6f\n', iter, x0,u, v)
%you can modify fprintf and diplay more decimal points.
while (err>tol)&(iter<=n)&(v~=0)
% ~= means not equal, equal is ==, two equal signs.
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.10f %12.10f %12.10f\n', iter,x0,u,err)
%you can modify fprintf and diplay more decimal points or less.
end
if(v==0)
disp(' division by zero')
end
if (iter>n)
disp(' Method failed to converge')
end
end
2. The Secant Method
function [ iter ] = mysecant1(f,x0,x1, tol,n)
%UNTITLED3 Summary of this function goes here--please write
% Detailed explanation goes here -please write
%
%
%
%
iter=0;
u=feval(f, x0);
v=feval(f,x1);
err=abs(x1-x0);
disp('-------------------------------------------')
disp('iter xn f(xn) |xn+1-xn| ')
disp('-------------------------------------------')
fprintf('%2.0f %12.6f %12.6f\n', iter, x0,u)
fprintf('%2.0f %12.6f %12.6f %12.6f\n', iter, x1, v, err)
%you can modify fprintf and diplay more decimal points.
while (err>tol)&(iter<=n)&((v-u)~=0)
x=x1-v*(x1-x0)/(v-u);
%see the formula for the secant line method.
x0=x1;
u=v;
x1=x;
v=feval(f,x1);
err=abs(x1-x0);
iter=iter+1;
fprintf('%2.0f %12.6f %12.6f %12.6f\n', iter,x1,v,err)
%you can modify fprintf and diplay more decimal points.
end
if((v-u)==0)
disp(' division by zero')
end
if (iter>n)
disp(' Method failed to converge')
end
end