function [ log ] = badLog10( x )
%badLog10 Should return the base 10 logarithm of its argument, but has
%one or more bugs.

% To find the base 10 logarithm of x, this uses bisection to search for
% a value r such that x - 10^r = 0. That r is the logarithm. A reasonable
% interval to search over is -1/x to 0 if x < 1, and 0 to x if x > 1. If
% x = 1, this immediately returns 0.

% Examples to use as test cases:
%   1 (result should be 0; boundary case)
%   10 (result should be 1; special case w/ log exactly 1)
%   100 (result should be 2; typical case w/ integer log)
%   2 (result should be about 0.301; typical case w/ non-integer log)
%   20 (result should be about 1.301; typical case w/ non-integer log > 1)
%   0.5 (result should be about -0.301; special case w/ input < 1)
%   3.5 (result should be about 0.5441; typical case w/ non-integer input)


% Decide what interval to search over, or return immediately for x = 1.

if x < 1
    log = bisect( x, -1/x, 0 );
elseif x > 1
    log = bisect( x, 0, x );
else
    log = 0;
end


    % Carry out the actual bisection search for log x, over interval [a,b].
    % Continue searching until the interval within which the logarithm lies
    % is at most 0.0001; take the midpoint of that interval as the actual
    % logarithm. Note that 10^a must be less than x, and 10^b greater, and
    % that this will remain true while this function runs.
    
    function r = bisect( x, a, b )
        
        tolerance = 0.0001;
        
        while b - a > tolerance
            mid = ( a + b ) / 2;
            if x - 10^mid > 0
                b = mid;
            elseif x - 10^mid < 0
                a = mid;
            else
                % Found logarithm exactly. Set a and b equal to it, to both
                % force the loop to stop and to set things up so that the
                % midpoint of the "interval" between them is the exact
                % logarithm.
                a = mid;
                b = mid;
            end
        end
        
        r = ( a + b ) / 2;
    end

end