| 1 |
xsun |
526 |
#include<stdlib.h> |
| 2 |
|
|
#include<stdio.h> |
| 3 |
|
|
#include<math.h> |
| 4 |
|
|
|
| 5 |
|
|
#define MYSEED 1234567 |
| 6 |
|
|
#define NTRIALS 100000000 |
| 7 |
|
|
|
| 8 |
|
|
/* double calculation(int trials) */ |
| 9 |
|
|
/* { */ |
| 10 |
|
|
/* int i, innerCount; */ |
| 11 |
|
|
|
| 12 |
|
|
|
| 13 |
|
|
/* // init the random number generator */ |
| 14 |
|
|
|
| 15 |
|
|
/* innerCount=0; */ |
| 16 |
|
|
/* for(i=0;i<trials;++i) */ |
| 17 |
|
|
/* { */ |
| 18 |
|
|
|
| 19 |
|
|
/* } */ |
| 20 |
|
|
/* pi= */ |
| 21 |
|
|
/* return pi; */ |
| 22 |
|
|
/* } */ |
| 23 |
|
|
|
| 24 |
|
|
|
| 25 |
|
|
int main(int argc, char* argv[]) |
| 26 |
|
|
{ |
| 27 |
|
|
int i,innerCount; |
| 28 |
|
|
double rms, diff; |
| 29 |
|
|
double x,y,rSqr,pi; |
| 30 |
|
|
FILE *outFile; |
| 31 |
|
|
|
| 32 |
|
|
outFile=fopen("pi","w"); |
| 33 |
|
|
fprintf(outFile,"#%s\t\t%s\n","number of trial","RMS"); |
| 34 |
|
|
|
| 35 |
|
|
srand48( MYSEED ); |
| 36 |
|
|
|
| 37 |
|
|
innerCount = 0; |
| 38 |
|
|
for(i=0;i<NTRIALS;i++){ |
| 39 |
|
|
x=(2.0*drand48())-1.0; |
| 40 |
|
|
y=(2.0*drand48())-1.0; |
| 41 |
|
|
rSqr= x*x + y*y; |
| 42 |
|
|
if(rSqr<=1.0) innerCount++; |
| 43 |
|
|
|
| 44 |
|
|
if( (i%100) == 0 ){ |
| 45 |
|
|
|
| 46 |
|
|
pi = 4.0*(double)innerCount / (double)i; |
| 47 |
|
|
diff = pi - M_PI; |
| 48 |
|
|
rms = sqrt( diff * diff ); |
| 49 |
|
|
|
| 50 |
|
|
fprintf(outFile,"%d\t\t%lf\n",i,rms); |
| 51 |
|
|
} |
| 52 |
|
|
} |
| 53 |
|
|
|
| 54 |
|
|
printf("\n"); |
| 55 |
|
|
printf("average of pi=%lf\n",pi); |
| 56 |
|
|
|
| 57 |
|
|
fclose(outFile); |
| 58 |
|
|
|
| 59 |
|
|
return 1; |
| 60 |
|
|
} |