UNB/ CS/ David Bremner/ teaching/ cs2613/ labs/ CS2613 Lab 24

Assignment 6

Time
25min
Activity
Discussion

Apparently people are confused about A6. Let's discuss.

Minmax

Time
25min
Activity
Small Groups
     function [minf, maxf] = minmax(fun, a,b)




     endfunction
    %!test
    %! [in,ax] = minmax(@(x)(x),-1,1);
    %! assert([in,ax]==[-1,1])

    %!test
    %! [in,ax] = minmax(@(x)(x.^2),-1,1);
    %! assert([in,ax],[0,1],1e-6)

Monte Carlo Integration I: Error bounds

Time
25min
Activity
Small Groups
    function [max_err, mean_err, std_err]= error_rate(reps, answer, fun, varargin)



    endfunction
    %!demo
    %! answer=quad(@sin, 0, pi)
    %! [mx, mn, std] = error_rate(100, answer, @mcintgr, @sin, 0, pi, 100)

    %!demo
    %! answer=quad(@sin, 0, pi)
    %! [mx, mn, std] = error_rate(100, answer, @mcintgr, @sin, 0, pi, 1000)

    %!demo
    %! fun=@(x)(x.^(4/3).*log(x)./cosh(x.^2 + x));
    %! answer=quad(fun, 1, e)
    %! [mx, mn, std] = error_rate(100, answer, @mcintgr, fun, 1, e, 100)

    %!demo
    %! fun=@(x)(x.^(4/3).*log(x)./cosh(x.^2 + x));
    %! answer=quad(fun, 1, e)
    %! [mx, mn, std] = error_rate(100, answer, @mcintgr, fun, 1, e, 1000)

Vectorized Monte Carlo integration

Time
25min
Activity
Small Groups

As usual, we want to try to vectorize our function. This is roughly based on function mcintgrv in GOBG Chapter 5.

Save following as ~fcshome/cs2613/labs/L24/mcintgrv.m, and follow the comments to complete the code.

function I = mcintgrv(fun, a, b, mcloops)

  [minf, maxf] = minmax(fun,a,b);

  ## find width of interval
  width= b-a;

  ## compute area of bounding rectangle
  area= width * maxf

  ## Choose mcloops places to sample, by generating random x values within the box

  x = a + _______  ___ rand(mcloops,1);

  ## Choose mcloops y values within the box
  y = maxf _________________________________________

  ## Evaluate the function on all of our x positions
  fx = _______________________________________

  ## Counts the number of sample points that lie under the graph
  counter = _______________________________________

  ## Esimate the integral
  I = (counter/mcloops)*area

endfunction