-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbisection.m
35 lines (35 loc) · 1.07 KB
/
bisection.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
function [xr,Ea,i,elapsedTime] = bisection(f,xl,xu,stoppingErrorCriteria,maxIterations)
tic
while xl>xu || xl==xu
fprintf('\nUpper x point should be greater than lower x point.\n')
xl = input('Lower x value: ');
xu = input('Upper x value: ');
end
plot(xl:0.01:xu,f(xl:0.01:xu),'k')
grid on; hold on
xr = (xl+xu)/2;
xrPrevious = xr;
for i=1:maxIterations
xr = (xl+xu)/2;
Ea = 100*abs((xr-xrPrevious)/xr);
if f(xl)*f(xr)<0
xrPrevious = xu;
xu = xr;
elseif f(xl)*f(xr)>0
xrPrevious = xl;
xl = xr;
end
if i>1 && Ea<stoppingErrorCriteria && abs(f(xr))<0.001
plot(xr,f(xr),'b*')
break
end
plot(xr,f(xr),'go')
hold on
end
if abs(f(xr))>0.001
xr = "No Root Found, please change the interval limits.";
Ea = "No Root Found, please change the interval limits.";
end
% title('Bisection Method - f(x) = x^2+x-14')
xlabel('x'); ylabel('y(x)')
elapsedTime = toc;