Files
OctaveFunctions/Bisection.m

43 lines
1.2 KiB
Matlab

function [xList,errorList] = Bisection(f, lowerValue, upperValue, allowError)
%
%Bisection(f, lowerValue, upperValue, allowError)
%Uses the bisection method to find the possible answers to the root of the function f
%
%Check that the number of input variables is correct
if(nargin ~= 4)
error('That is not the correct number of arguments')
end
%A few necesary things before we begin
pkg load symbolic;
warning('off','OctSymPy:sym:rationalapprox');
%Constant Variables
maxItterations = 50;
%Variables
cnt = 1;
errorValue = 1;
currentValue = 0.0;
%If the lower and upper bounds are mixed up swap them
if(double(subs(f,lowerValue)) > 0)
[lowerValue,upperValue] = swap(lowerValue, upperValue);
end
%Loop until the error is within bounds or the Maximum number of iterations is reached
while((abs(errorValue) > allowError) && (cnt < maxItterations))
currentValue = (lowerValue + upperValue)/ 2;
errorValue = double(subs(f,currentValue));
%Replace the correct value with the new value
%if error == 0 then the value has been found
if(errorValue < 0)
lowerValue = currentValue;
else
upperValue = currentValue;
end
xList(cnt) = currentValue;
errorList(cnt) = errorValue;
++cnt;
end
end