Thursday, April 14, 2011

Here's a piece of what I did today: Hooray Matlab!

function [p,ite] = bisect(fstring,a,b,tol)
%[p,ite] = bisect(fstring,a,b,tol)
%   Bisect uses bisection method to solve a nonlinear equation f(x) = 0 on
%   interval a,b. fstring is nonlinear function as a string, and tol is the
%   tolerance to stop the iteration.
%   Returns, p the approximate zero, and ite the number of iterations used
%   Stopping Criterion: |f(p)| <= tol
%   NOTE: fstring must be continuous between a and b!
%   Author: Ryan Boyer

f = inline(fstring);

y_a = feval(f,a);
y_b = feval(f,b);

if y_a == 0
    p = a;
    ite = 0;
    return
elseif y_b == 0
    p = b;
    ite = 0;
    return
end

%check to make sure bisection applies, that is y_a and y_b have different
%signs
if y_a * y_b > 0
    fprintf('Error: y_a and y_a do not have opposite signs\n');
    fprintf('Bisection method does not apply\n');
    return
end

%set up loop
p = (a + b)/2;
ite = 0;
y_p = feval(f,p);
%loop
while abs(y_p) > tol
    if y_a * y_p < 0 %y_a and y_p have opposite signs
        b = p;
        p = (a + b)/2;
    else
        a = p;
        p = (a + b)/2;
    end
    
ite = ite + 1;
y_p = feval(f,p);
y_b = feval(f,b);
y_a = feval(f,a);
end
end


Any questions? Glad your calculator does this for you? Well, it doesn't, it uses faster methods than this.

This wasn't a particularly hard problem, but it had lots of strings and loops and notes so it turned out colorful and I thought I would share another glimpse into what I get to do as a math major.

3 comments:

  1. it finds the zero of a function within the interval (a,b) as long f(a) and f(b) have opposite signs.

    basically it averages a and b, then tests that point then averages a or b with the new point depending on the new point and then averages and tests again and repeat. It goes until the value is within the tolerance level, meaning your approximation is close enough.

    ReplyDelete