-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMC_pi.c
46 lines (41 loc) · 1.45 KB
/
MC_pi.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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
# include <math.h>
//int main(int argc, char *argv[]) {
int main() {
//int N = atoi(argv[1]);// read iteration time from command line
int N = 500000;// iteration number
printf ("time(0) is %ld\n",time(0));// seconds from Jan. 01 1970 (epoch time)
srand(time(NULL));// time(0) is also ok
int sum = 0;
int i,counter = 0;
double error = 1e-10;
double oldPi = 1,newPi = 1;// initial values can't be zero!!!
double temp = 100;// temp is the evaluation for while loop
for(i = 1; i <= N; i++) {
double x = (double) rand() / RAND_MAX;
double y = (double) rand() / RAND_MAX;
if((x * x + y * y) < 1) {
sum++;
}
//printf("After interation %d, PI = %f\n",i,(double) 4 * sum / (N));
}
printf("PI = %f\n", (float) (sum)/(float) (N) * 4.0 );
// Please make a plot to tell when Pi is close to a constant
//while(temp > error){
// counter++;
// double x = (double) rand() / RAND_MAX;
// double y = (double) rand() / RAND_MAX;
// if((x * x + y * y) < 1) {
// sum++;
// }
//
// oldPi = newPi;
// newPi = (double) 4 * sum / (counter);
// temp = (double)(fabs(newPi-oldPi))/oldPi;// abs() for integer only
//
// printf("After interation %d, PI = %.12lf with error %.12lf\n",counter,(double) 4 * sum / (counter),temp);
//}
return 0;
}