bisection Algorithm

The bisection algorithm, also known as binary search or interval halving method, is a root-finding approach that narrows down the search interval by repeatedly dividing it in half. This algorithm is based on the intermediate value theorem and works on the premise that if a continuous function has values of opposite signs at two points within an interval, then it must have a root within that interval. The bisection method is especially effective for solving nonlinear equations with a single variable and is guaranteed to converge to a root if the function is continuous and the initial interval contains a root. To implement the bisection algorithm, start by defining an initial interval [a, b] such that the function f(a) and f(b) have different signs. Then, compute the midpoint c = (a + b) / 2 and evaluate the function f(c). If f(c) is sufficiently close to zero or the specified tolerance, c is considered as the root. Otherwise, the algorithm checks the sign of f(c) and updates the interval [a, b] accordingly: if f(a) and f(c) have opposite signs, the new interval becomes [a, c], and if f(b) and f(c) have opposite signs, the interval becomes [c, b]. Repeat this process iteratively until the desired root is found or a maximum number of iterations is reached. The bisection algorithm is not the fastest root-finding method, but it is simple to implement and provides a robust and reliable means to find a root within a given interval.
%The bisection method for finding the root of a function.
%f(a) is < 0 and f(b) > 0. By the intermediate value theorem,
%there exists a number c in between a and b such that f(c) = 0.
%In other words, there is always a root in between f(a) and f(b).
%The bisection method takes the midpoint between a and b and evaluates
%the value of the function at the midpoint. If it is less than 0,
%a is assigned the midpoint. If it is greater than 0, b is assigned the
%midpoint. With each iteration, the interval the root lies in is halved,
%guaranteeing that the algorithm will converge towards the root.

%INPUTS:
%Function handle f
%endpoint a
%endpoint b
%maximum tolerated error

%OUTPUTS:
%An approximated value for the root of f within the defined interval.

%Written by MatteoRaso

function y = bisection(f, a, b, error)
  %Making sure that the user didn't input invalid endpoints.
  if ~(f(a) < 0)
    disp("f(a) must be less than 0")
  elseif ~(f(b) > 0)
    disp("f(b) must be greater than 0")
  else 
    c = 1e9;
    %Loops until we reach an acceptable approximation.
    while abs(f(c)) > error
      c = (a + b) / 2;
      if f(c) < 0
        a = c;
      else
        b = c;
      endif
      disp(f(c))
    endwhile
    x = ["The root is approximately located at ", num2str(c)];
    disp(x)
    y = c;
  endif
endfunction

LANGUAGE:

DARK MODE: