Lab
1: Estimation of
Requirements
Understand how to generate pseudorandom numbers under Linux using C/C++.
Implement two algorithms to estimate the constant PI (== 3.14 ...) using Monte Carlo simulation techniques.
Compare the two algorithms and tell which one is better.
Random Number Generation under Linux
See
"man random" for information about how to use the standard
1.
Repeated calls to the function return "pseudorandom" (which
#include <iomanip.h>
#include<stdlib.h>
int main(){
cout
<< random() << endl << random() << endl;
}
produces
this output:
846930886
1804289383
2.
Because these values are algorithmically generated, you get the
3.
These integer values are uniformly distributed over the range
Algorithm
1
Repeat
the
a)
generate x and y as two uniform random real values between 0 and 1
b)
use these two values as the coordinates of a point randomly
c)
test whether this random point is also inside a unit circle
distance = x^2 + y^2
d)
if distance <= 1 then increment a success counter, S, otherwise
After
completing the N iterations, form the ratio (S / N). Since the
PI~= 4 * S / N
Algorithm
2
Instead
of looking at the overlap between a 1/4 circle and the unit square, let's split
the square diagonally from upper left [i.e., point (0,1)] to lower right [i.e.,
point (1,0)]. Notice that the boundary of the 1/4 circle is entirely contained
in the upper triangle [i.e., away from the origin point (0,0)] so we can
restrict our experiment to generating points in that triangle.
Notice that the equation of the diagonal straight line forming the lower
boundary of the triangle is
x+y=1
and whenever x+y<1 then we have that:
(1-x) + (1-y)
= 2 - (x+y)
> 2 - 1
= 1
Furthermore, the area of the upper triangle is clearly 1/2, whereas the area of
the "lens" shaped intersection of the 1/4 circle and the upper
triangle is
PI/4 - 1/2
== (PI - 2) / 4
Thus, if we modify step (b) of the algorithm 1 like this:
b) use these two values as the coordinates of a point randomly distributed over
the unit square, which goes from (0,0) on the bottom left corner to (1,1) on the
top right corner. However, if x+y
< 1, then modify them as follows:
x = 1-x
y = 1-y
Then the ratio (S/N) becomes an estimate of [(PI - 2) / 4] / [(1 / 2)], or
equivalently:
PI ~= 2 *
(S/N) + 2
Notice that with this second version of the algorithm, the estimate of PI must
be between 2 and 4 (rather than between 0 and 4).
Last Update: 04/22/2004