Numerical Integration: Monte Carlo integration
A Monte Carlo method
In scientific computing, a Monte Carlo method is also popular. A Monte Carlo method is an approach to solving a mathematical problem by generating an appropriate number of randomly drawn points and determining the fraction of points with a requested property.
Monte Carlo integration of a function on an interval is based on calculating the area of an area under the curve—we denote this region under the curve as and its area as —via the following approach. Choose a region that includes and for which you know or can easily calculate the area ; usually a rectangle is chosen for , but this is not necessarily the case. Now randomly generate a number of points within the region and determine how many points are within the sub-region and how many are not. You can then estimate the area of as the area of the region times the fraction of the number of points that fall within in the sample.
Once the region has been chosen, the Monte Carlo integration method boils down to the following (see the figure below):
- Take a sufficiently large uniform sample of points in the region.
- Determine the fraction of points that lie within the sub-region .
- .
The figure above suggests that one chooses the region as closely as possible around the region. but this is not necessary. The steps of the Monte Carlo algorithm of numerically approximating on the interval for a nonnegative function can be written down as follows::
Step 1. Choose a rectangular region of points for which and with appropriately chosen such that The basic idea is to remove from the area under the graph of as many pieces of which you already know the surface.
Step 2. Take a sufficiently large uniform sample of points in the region . This can be done by a uniform drawing of values from and an equally sized uniform drawing of values from .
Step 3. Name a point in 'good' when . Note that this definition is only applicable to a positive function; with a negative function, the definition of goodness is just the opposite. The general case can also be treated, possibly by splitting the interval over which integration takes place into parts where the function is only positive or only negative. We call a point 'wrong' if it is not 'good'. In your sample, count the number of 'good' points ( ) and the number of 'wrong' points ( ).
Step 4. The area under the graph within the region is now given by
Step 5. Now determine the numerical approximation of on the interval by adding the areas of the missing pieces to the result of the previous step.
Python task
Write your own function MonteCarloIntegral(f, a, b, sampleSize=1000)
that implements the steps above.
Apply your function with a sample size of points in the following two cases: