Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Matlab Problem... Problem 4 Consider \"mybisect\" function given to you in class

ID: 2081863 • Letter: M

Question

Matlab Problem...

Problem 4 Consider "mybisect" function given to you in class. This function implements the bisection algorithm: function r mybisect (fun, x tol tol) bisect: Use Bisection algorithm to find a root of the scalar equation f (x 0 Synposis r bisect fun, xb, xtol, tol) Input fun (string) name of function for which roots are sought vector of bracket endpoints xb (1) -a, xb (2) b xb relative x tolerance Default: xtol 5 eps xtol tol relative f (x) tolerance fault ftol 5 eps output r root (or singularity) of the function in xb (1) ,xb (2) J a b (1) b (2)

Explanation / Answer

a)

    if(abs(fm)<ftol)|(abs(dx)<xtol)

        r=xm;

        return

    end

b)

It fails when f(a) and f(b) have the same sign at each step.

c)

%CALLING FILE

clc;

close all;

clear all;

tol = 1.0E-5;

x = [-1 3];

root = myfun(x,tol)

%myfun.m

function fn = myfun( x,tol)

fun = @(x) x.^3 -2*x -10;

fn = mybisect(fun,x,2,tol);

return;

end

%mybisect.m

function r = mybisect(fun,xb,xtol,ftol )

a = xb(1); b = xb(2);

fa = feval(fun,a); fb = feval(fun,b);

if sign(fa)==sign(fb)

    error(sprintf('Root not bracketed by [%f %f]',a,b));

end

k = 0; maxit = 100;

while k<maxit

    k=k+1

    dx=b-a;

    xm=a+0.5*dx;

    fm=feval(fun,xm);

    if(abs(fm)<ftol)|(abs(dx)<xtol)

        r=xm;

        return

    end

    if sign(fm)==sign(fa)

        a=xm;fa=fm;

    else

        b=xm;fb=fm;

    end

    if k<3

        sprintf('%d %2.2f %2.2f %2.2f %2.2f %2.2f %2.2f',k,xm,fm,a,fa,b,fb)

    end

end

warning(sprintf('root not within tolerance after %d iteratins ',k));

k   xm       fm    a       fa       b    fb

1   1.00   -11.00   1.00 -11.00 3.00   11.00

2   2.00   -6.00     2.00 -6.00    3.00 11.00