Advertisement
Guest User

Secant

a guest
Apr 21st, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Octave 1.09 KB | None | 0 0
  1. function secant_method()
  2.     f = @(x) x^2 - 9;
  3.     eps = 1e-6;
  4.     x0 = 1000;  x1 = x0 - 1;
  5.     [solution,no_iterations] = secant(f, x0, x1, eps);
  6.     if no_iterations > 0   % Solution found
  7.         fprintf('Number of function calls: %d\n', 2 + no_iterations);
  8.         fprintf('A solution is: %f\n', solution)
  9.     else
  10.         fprintf('Abort execution.\n')
  11.     end
  12. end
  13.  
  14. function [solution,no_iterations] = secant(f, x0, x1, eps)
  15.     f_x0 = f(x0);
  16.     f_x1 = f(x1);
  17.     iteration_counter = 0;
  18.     while abs(f_x1) > eps && iteration_counter < 100
  19.         try
  20.             denominator = (f_x1 - f_x0)/(x1 - x0);
  21.             x = x1 - (f_x1)/denominator;
  22.         catch
  23.             fprintf('Error! - denominator zero for x = \n', x1)
  24.             break
  25.         end
  26.         x0 = x1;
  27.         x1 = x;
  28.         f_x0 = f_x1;
  29.         f_x1 = f(x1);
  30.         iteration_counter = iteration_counter + 1;
  31.     end
  32.     % Here, either a solution is found, or too many iterations
  33.     if abs(f_x1) > eps
  34.         iteration_counter = -1;
  35.     end
  36.     solution = x1;
  37.     no_iterations = iteration_counter;
  38. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement