In: Electrical Engineering
script for Secant Method. Using Matlab or Octave.
The data:
y = x.^2 - 1.2
x_lower = 0.4
x_upper = 0.6
Es = 0.5*10^(2-n)
n = 5
Matlab Program-1:
a=input('Enter given function:','s');
f=inline(a)
x(1)=input('Enter the first point of guess interval: ');
x(2)=input('Enter the second point of guess interval: ');
n=input('Enter the allowed Error in calculation: ');
iteration=0;
for i=3:1000
x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) -
f(x(i-2))));
iteration=iteration+1;
if abs((x(i)-x(i-1))/x(i))*100<n
root=x(i)
iteration=iteration
break
end
end
Result :
Enter function:x.^2 -1.2
f =
Inline function:
f(x) = x.^2 -1.2
Enter the first point of guess interval: 0.4
Enter the second point of guess interval: .6
Enter the allowed Error in calculation: 0.5*10^-3 ( Es =
0.5*10^(2-n) where n = 5
root =
1.0954
iteration =
6
or
Matlab program- 2:
function secant_method()
f = @(x) x^2 - 1.2;
n=5;
eps = 0.5.*10^(2-n);
x0 =0.6; x1 = x0 - 0.001;
[solution,no_iterations] = secant(f, x0, x1, eps);
if no_iterations > 0 % Solution found
fprintf('Number of function calls: %d\n', 2 + no_iterations);
fprintf('A solution is: %f\n', solution)
else
fprintf('Abort execution.\n')
end
end
function [solution,no_iterations] = secant(f, x0, x1, eps)
f_x0 = f(x0);
f_x1 = f(x1);
iteration_counter = 0;
while abs(f_x1) > eps && iteration_counter <
100
try
denominator = (f_x1 - f_x0)/(x1 - x0);
x = x1 - (f_x1)/denominator;
catch
fprintf('Error! - denominator zero for x = \n', x1)
break
end
x0 = x1;
x1 = x;
f_x0 = f_x1;
f_x1 = f(x1);
iteration_counter = iteration_counter + 1;
end
% Here, either a solution is found, or too many iterations
if abs(f_x1) > eps
iteration_counter = -1;
end
solution = x1;
no_iterations = iteration_counter;
end
Result:
Number of function calls: 6
A solution is: 1.095563