Skip to content

Instantly share code, notes, and snippets.

@hyobyun
Last active December 18, 2015 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyobyun/5860230 to your computer and use it in GitHub Desktop.
Save hyobyun/5860230 to your computer and use it in GitHub Desktop.
function [ x ] = bisectionSearch( y, fn ,e )
% BISECTIONSEARCH Searches for x that results in y for function fn with max
% error e between a<=x<=b, or until iteration does not change value of y
% FUNCTION MUST BE MONOTONIC
% Hyo Byun
% Mayberg Lab, Emory University
% 2013
% Set bounds
a=0;
b=1;
ss=(fn(b)-fn(a))/abs(fn(b)-fn(a)); % Get sign of monotnic function slope
oldY=-1; % set oldY
curY=fn((a+b)/2); % init current Y
% While the solution is outside error bounds & if iteration hasn't changed y, quit
while (abs(curY-y)>e && oldY~=curY)
%Update middle of bisection search
if( (ss>0 && curY<y) || (ss<0 && curY >y) )
a=(a+b)/2;
else
b=(a+b)/2;
end
oldY=curY;
curY=fn((a+b)/2);
%fprintf('%d \n', curY);
end
fprintf('x=%f, y= %f \n',(a+b)/2, curY);
x=(a+b)/2;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment