-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindroot.m
More file actions
54 lines (40 loc) · 1.1 KB
/
findroot.m
File metadata and controls
54 lines (40 loc) · 1.1 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
function xk = findroot(guess)
% Finds the root of a function y=f(x) using Newton's method
tol = 10^(-9); %the tolerence, how accurate we want our answer to be
maxk = 100; %maximum itteration count
k = 0;
q = 0;
xkm2 = guess; %x_(k-2)
xkm1 = guess; %x_(k-1)
xk = guess; %x_k
%print the zero'th itteration first
formatSpec = 'k = %i | x = %f | f(x) = %f | q = %f\n';
fprintf(formatSpec,[k,xk,f(xk),q])
k=k+1;
%loop until within tolerence or max itterations it met
while k <= maxk
xkm2 = xkm1;
xkm1 = xk;
xk = xkm1 - f(xkm1) / fprime(xkm1);
%note the q formula is not defined for k<2 since x for k<0 is not defined
if k>=2
q = log(f(xk)/f(xkm1))/log(f(xkm1)/f(xkm2));
else
q=0;
end
fprintf(formatSpec,[k,xk,f(xk),q])
k = k+1;
%check if we are close enough to zero
if abs(xk - xkm1) < tol
break
end
end
end
function y = f(x)
%The function we are trying to find the root of
y = tan(x./4) - 1;
end
function z = fprime(x)
%The derivative of the function we are trying to find the root of
z = sec(x./4).^2 ./4;
end