A cura di Giuseppe Ciaburro
Pubblicato il 04/06/2007
Un metodo iterativo per la risoluzione dell'algoritmo della secante
%function [p1,err,k,y]=secant(f,p0,p1,delta,epsilon,max1)
%Input - f is the object function input as a string 'f'
% - p0 and p1 are the initial approximations to a zero of f
% - delta is the tolerance for p1
% - epsilon is the tolerance for the function values y
% - max1 is the maximum number of iterations
%Output - p1 is the secant method approximation to the zero
% - err is the error estimate for p1
% - k is the number of iterations
% - y is the function value f(p1)
while 1
clear, clf,clc
fprintf( '\n============================================\n' );
fprintf( ' Secant Method \n' );
while 1
fprintf( ' \n The absciss extremes a and b (a < b)')
fprintf( ' \n a = '); a = input('');
fprintf( ' b = '); b = input('');
if a < b; break; end
fprintf( ' \n a should be less than b! ')
fprintf( ' \n Repeat your input for a and b! ')
end
fprintf( ' \n Now the function is plotted \n')
x=a:0.1:b;
f = feval('f306',x);
plot(x, f, 'b-');
centaxes
hold on;
fprintf( '** Give the Po, first initial abscissa value approximation to a zero of f:\n');
p0 = input('Initial approximation Po = ');
fprintf( '** Give the P1, second initial abscissa value approximation to a zero of f:\n');
p1 = input('Initial approximation P1 = ');
while 1
fprintf( '\n Input the tolerance value for P1, delta = ')
delta = input('');
if delta < 1 & delta > 0; break; end
fprintf( ' \n Delta should be greater than 0 and less than 1!!! ')
fprintf( ' \n Repeat your input for tolerance value! ')
end
while 1
fprintf( '\n Input the tolerance value for the function Y values, epsilon = ')
epsilon = input('');
if epsilon < 1 & epsilon > 0; break; end
fprintf( ' \n Epsilon should be greater than 0 and less than 1!!! ')
fprintf( ' \n Repeat your input for tolerance value! ')
end
while 1
fprintf( '\n Input the maximum number of iterations, N_max = ')
max1 = input('');
if max1 > 1; break; end
fprintf( ' \n The number of iterations should be greater than 1!!! ')
fprintf( ' \n Repeat your input for the number of iterations value! ')
end
for k=1:max1
p2=p1-feval('f306',p1)*(p1-p0)/(feval('f306',p1)-feval('f306',p0));
err=abs(p2-p1);
relerr=2*err/(abs(p2)+delta);
p0=p1;
p1=p2;
y=feval('f306',p1);
if (err<delta)|(relerr<delta)|(abs(y)<epsilon),break,end
end
fprintf('\n==============RESULTS================')
fprintf('\n P1 is the Secant approximation to zero = %12.6f', p1);
fprintf('\n Err is the error estimate for P1 = %12.6f', err);
fprintf('\n K is the number of iterations = %u', k);
fprintf('\n Y is the function value f(P1) = %12.6f', y);
fprintf('\n============================================')
kont1 = input( 'Type 1 to continue, or 0 to stop: ' );
if kont1 == 0, break; end
end