-
Notifications
You must be signed in to change notification settings - Fork 0
/
falsePosition.m
81 lines (67 loc) · 1.87 KB
/
falsePosition.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function [i,root,data,timeElapsed] = falsePosition(f,lower, upper, epsilon, maxNumberOfIterations)
tic;
data = 0;
root = 0;
if (f(lower) * f(upper) > 0)
i = 0;
timeElapsed = toc;
errordlg('There is no change in the sign of the function over this interval.');
return;
elseif f(lower) == 0
i = 1;
root = lower;
data(1,1) = lower;
data(1,2) = f(lower);
data(1,3) = upper;
data(1,4) = f(upper);
data(1,5) = lower;
data(1,6) = f(lower);
data(1,7) = 0;
timeElapsed = toc;
return;
elseif f(upper) == 0
i = 1;
root = upper;
data(1,1) = lower;
data(1,2) = f(lower);
data(1,3) = upper;
data(1,4) = f(upper);
data(1,5) = upper;
data(1,6) = f(upper);
data(1,7) = 0;
timeElapsed = toc;
return;
else
root = ((lower*f(upper)) - (upper*f(lower))) / (f(upper) - f(lower));
approximateError = 100;
i = 1;
previousRoot = 0;
while true
% data(i,1) = i;
data(i,1) = lower;
data(i,2) = f(lower);
data(i,3) = upper;
data(i,4) = f(upper);
data(i,5) = root;
data(i,6) = f(root);
if (i > 1)
approximateError = abs((root - previousRoot)/root) * 100;
end
data(i,7) = approximateError;
%fprintf('%2i %f %f %f %f %f %f %f\n', i, lower, f(lower), upper, f(upper), root, f(root), approximateError);
if (f(lower) * f(root) < 0)
upper = root;
else
lower = root;
end
[done] = checkConditions(i, maxNumberOfIterations, approximateError, epsilon, f, root);
if (done == true)
break;
end
i = i + 1;
previousRoot = root;
root = ((lower*f(upper)) - (upper*f(lower))) / (f(upper) - f(lower));
end
end
timeElapsed = toc;
end