1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Trouble with bisect function

  1. Jun 20, 2016 #1
    1. The problem statement, all variables and given/known data
    I'm not really sure how to define my bisect function.. I included my work and question in the images attached.

    2. Relevant equations


    3. The attempt at a solution
     

    Attached Files:

    Last edited: Jun 20, 2016
  2. jcsd
  3. Jun 20, 2016 #2
    I guess I was thinking it was a built in function in matlab, I've tried to look at a few examples of bisection codes and I'm not super sure how to format it to make it work with this problem.
     
  4. Jun 20, 2016 #3
    function [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,varargin)
    % bisect: root location zeroes
    % [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,p1,p2,...):
    % uses bisection method to find the root of func
    % input:
    % func = name of function
    % xl, xu = lower and upper guesses
    % es = desired relative error (default = 0.0001%)
    % maxit = maximum allowable iterations (default = 50)
    % p1,p2,... = additional parameters used by func
    % output:
    % root = real root
    % fx = function value at root
    % ea = approximate relative error (%)
    % iter = number of iterations
    if nargin<3,error('at least 3 input arguments required'),end
    test = func(xl,varargin{:})*func(xu,varargin{:});
    if test>0,error('no sign change'),end
    if nargin<4|isempty(es), es=0.0001;end
    if nargin<5|isempty(maxit), maxit=50;end
    iter = 0; xr = xl; ea = 100;
    while (1)
    xrold = xr;
    xr = (xl + xu)/2;
    iter = iter + 1;
    if xr ~= 0,ea = abs((xr - xrold)/xr) * 100;end
    test = func(xl,varargin{:})*func(xr,varargin{:});
    if test < 0
    xu = xr;
    elseif test > 0
    xl = xr;
    else
    ea = 0;
    end
    if ea <= es | iter >= maxit,break,end
    end
    root = xr; fx = func(xr, varargin{:});
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted