-
Notifications
You must be signed in to change notification settings - Fork 0
/
newtonRaphson.m
52 lines (37 loc) · 964 Bytes
/
newtonRaphson.m
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
function [i,root,data,timeElapsed] = newtonRaphson(f, xi, epsilon, maxNumberOfIterations)
tic;
data = 0;
root = 0;
i = 1;
syms x
differentiation = eval(['@(x)' char(diff(f(x)))]);
if f(xi) == 0
root = xi;
data(1,1) = xi;
data(1,2) = 0;
data(1,3) = differentiation(xi);
data(1,4) = xi;
data(1,5) = 0;
timeElapsed = toc;
return;
end
%x(i+1) = x(i) - f(x) / f'(x)
while true
root = xi - (f(xi)/differentiation(xi));
approximateError = abs((root - xi)/root) * 100;
% data(i,1) = i;
data(i,1) = xi;
data(i,2) = f(xi);
data(i,3) = differentiation(xi);
data(i,4) = root;
data(i,5) = approximateError;
%fprintf('%2i %f %f %f \n', i, xi, root, approximateError);
[done] = checkConditions(i, maxNumberOfIterations, approximateError, epsilon, f, root);
if (done == true)
break;
end
i = i + 1;
xi = root;
end
timeElapsed = toc;
end