-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecant.m
More file actions
43 lines (31 loc) · 1.07 KB
/
secant.m
File metadata and controls
43 lines (31 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
% func --> function is taken by user
% like @(x)(sin(x)) or @(x)(x^2 + x - 1) or any other function
% but use the same format i.e. use paranthesis as used above with '@' and 'x'
% maxerr --> Maximum Error in finding Root
clc;
clear;
maxiter = 100; % max number of iteration before get the answer
f1 = input('Enter the function f(x): ','s');
f = inline(f1);
xn_2 = input('Ener Lower Limit: ');
xn_1 = input('Ener Upper Limit: ');
maxerr = input('Enter Maximum Error: ');
xn = (xn_2*f(xn_1) - xn_1*f(xn_2))/(f(xn_1) - f(xn_2));
disp('xn-2 f(xn-2) xn-1 f(xn-1) xn f(xn)');
disp(num2str([xn_2 f(xn_2) xn_1 f(xn_1) xn f(xn)],'%20.7f'));
flag = 1;
while abs(f(xn)) > maxerr
xn_2 = xn_1;
xn_1 = xn;
xn = (xn_2*f(xn_1) - xn_1*f(xn_2))/(f(xn_1) - f(xn_2));
disp(num2str([xn_2 f(xn_2) xn_1 f(xn_1) xn f(xn)],'%20.7f'));
flag = flag + 1;
if(flag == maxiter)
break;
end
end
if flag < maxiter
display(['Root is x = ' num2str(xn)]);
else
display('Root does not exist');
end