% Matlab script to illustrate the method of interval bisection
% to solve a nonlinear equation

% this particular script brackets the square root of a number M
% (input by the user) by 2 adjacent floating-point numbers 

% note that the function we are trying to zero is f(x) = x^2 - M.

format long

% an example of getting user input
M = input('Please enter the number whose square root you want: ')
a = input('Please enter left end of bracket: ')
b = input('Please enter right end of bracket: ')

% an example of input error checking
if (a >= b)
    error('*ERR* Bracket was not specified from left to right.')
end

if sign(a^2-M) == sign(b^2-M),
    error('*ERR* Interval does not bracket root.')
end

% iteration counter
k = 0;
while b-a > eps*max(abs(a),abs(b)) 
    x = (a + b)/2;
    if sign(x^2-M) == sign(b^2-M)
      b = x
    else
      a = x
    end
    k = k + 1
    disp('Hit return to continue')
    pause 
end