-
Notifications
You must be signed in to change notification settings - Fork 0
/
MonteCarlo.c
70 lines (43 loc) · 1.3 KB
/
MonteCarlo.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "Random.h"
/**
Estimate Pi by approximating the area of a circle.
How: generate N random numbers in the unit square, (0,0) to (1,1)
and see how are within a radius of 1 or less, i.e.
<pre>
sqrt(x^2 + y^2) < r
</pre>
since the radius is 1.0, we can square both sides
and avoid a sqrt() computation:
<pre>
x^2 + y^2 <= 1.0
</pre>
this area under the curve is (Pi * r^2)/ 4.0,
and the area of the unit of square is 1.0,
so Pi can be approximated by
<pre>
# points with x^2+y^2 < 1
Pi =~ -------------------------- * 4.0
total # points
</pre>
*/
static const int SEED = 113;
double MonteCarlo_num_flops(int Num_samples)
{
/* 3 flops in x^2+y^2 and 1 flop in random routine */
return ((double) Num_samples)* 4.0;
}
double MonteCarlo_integrate(int Num_samples)
{
Random R = new_Random_seed(SEED);
int under_curve = 0;
int count;
for (count=0; count<Num_samples; count++)
{
double x= Random_nextDouble(R);
double y= Random_nextDouble(R);
if ( x*x + y*y <= 1.0)
under_curve ++;
}
Random_delete(R);
return ((double) under_curve / Num_samples) * 4.0;
}