function Secant1(a,b,nmax,ep) % Cheney/Kincaid 5th Ed., Page 127. % Secant Method with a maximum number of iterations and % a fixed value for epsilon. % You must provide a starting interval [a,b] = [x_0,x_1]. % nmax = max iterations % ep = max error for convergence of d tic % We will use the example on p. 128. % f(x) = x^5 + x^3 + 3 in [-1,1]. % I used: % Secant1(-1,1,100,1e-10) f = @(x) x^5 + x^3 + 3; % Initialize f(a) & f(b). fa = f(a); fb = f(b); % We must ensure that abs(fa)<=abs(fb). % If necessary, swap a & b, using c & fc as temp storage. if abs(fa) > abs(fb) c = a; a = b; b = c; fc = fa; fa = fb; fb = fc; end % I guess we can start a table. fprintf(' n x_n f(x_n)\n'); fprintf(' 0 %20.17f %20.17f\n',a,fa); fprintf(' 1 %20.17f %20.17f\n',b,fb); % We will run nmax iterations (or fewer). for i=2:nmax % We must ensure that abs(fa)<=abs(fb). [See above!] if abs(fa) > abs(fb) c = a; a = b; b = c; fc = fa; fa = fb; fb = fc; end % Calculate the new value of x for this iteration. d = (b - a)/(fb - fa); b = a; fb = fa; d = d*fa; % If abs(d) < epsilon, then we have convergence. if abs(d) < ep fprintf('Convergence; abs(d) < epsilon\n'); toc return; end % Output the new value of x, which is now "a". a = a - d; fa = f(a); fprintf('%3d %20.17f %20.17f\n',i,a,fa); end % We've run out of iterations! fprintf('Did not converge!\n'); toc