-
Notifications
You must be signed in to change notification settings - Fork 0
/
bisectionmethod.m
39 lines (39 loc) · 1.12 KB
/
bisectionmethod.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
function m = bisectionmethod(low, high, tol)
disp('Bisection Method');
% Evaluate both ends of the interval
f=@(x)(5*x^4 - 2.7*x^2 - 2*x + .5);
y1 = feval(f, low);
y2 = feval(f, high);
i = 0;
% Display error and finish if signs are not different
if y1 * y2 > 0
disp('Have not found a change in sign. Will not continue...');
m = 'Error'
return
end
% Work with the limits modifying them until you find
% a function close enough to zero.
disp('Iter low high x0');
while (abs(high - low) >= tol)
i = i + 1;
% Find a new value to be tested as a root
m = (high + low)/2;
y3 = feval(f, m);
if y3 == 0
fprintf('Root at x = %f \n\n', m);
return
end
fprintf('%2i \t %f \t %f \t %f \n', i-1, low, high, m);
% Update the limits
if y1 * y3 > 0
low = m;
y1 = y3;
else
high = m;
end
end
% Show the last approximation considering the tolerance
w = feval(f, m);
fprintf('\n x = %f produces f(x) = %f \n %i iterations\n', m, y3, i-1);
fprintf(' Approximation with tolerance = %f \n', tol);
endfunction