- #1
gfd43tg
Gold Member
- 950
- 50
Homework Statement
Complete the following MATLAB function that computes the integral ##\int_{-2}^{5} f(x)dx## of the function
##f(x)## plotted in the figure below, after N trials using a Monte Carlo method. Take all the required
numerical inputs from the figure shown below.
Hint: Generate a set of ##N## uniformly distributed random points ##(x, y)## within a rectangular area
and determine the fraction of them that fall within the area of interest (i.e., under ##f(x)##).
Code:
function val = mcIntegral(fh,N)
% Inputs: fh: the function handle to vectorized function f(x)
% -2, 5: the lower and upper integration bounds
% N: the number of trials
% Output: val: the calculated value of the integral
A =_______________________________________________________;% enclosing area
x = rand( )
___________________________________________________________________
y = rand( )
___________________________________________________________________
success =_________________________________________________________;
val = A * success / N ;
Homework Equations
The Attempt at a Solution
I have never heard of Monte Carlo, but this was given on a previous exam. I am wondering if one could reasonably answer this question without ever hearing about the method, and how I will be able to do it?? It obviously has something to do with probability. My guess is A is supposed to be a rectangle with a width of ##5- (-2) = 7## by height of the max value of the function, but I don't know how to get that maximum. I also don't know what to do with success, or if x and y are okay.
Code:
function val = mcIntegral(fh,N)
A = ? [7 max fh(x)]
x = rand(N,1);
y = rand(N,1);
success = (x <= 5) && (x >= -2) && (y <= fh(x))
val = A*success/N
Attachments
Last edited: