root / Pi / C / Simple / Pi.c @ 125
Historique | Voir | Annoter | Télécharger (2,1 ko)
1 |
//
|
---|---|
2 |
// Estimation of Pi using Monte Carlo exploration process
|
3 |
// gcc -std=c99 -O3 -o Pi Pi.c -lm
|
4 |
//
|
5 |
|
6 |
#include <math.h> |
7 |
#include <stdio.h> |
8 |
#include <stdlib.h> |
9 |
#include <limits.h> |
10 |
|
11 |
// Marsaglia RNG very simple implementation
|
12 |
#define znew ((z=36969*(z&65535)+(z>>16))<<16) |
13 |
#define wnew ((w=18000*(w&65535)+(w>>16))&65535) |
14 |
#define MWC (znew+wnew)
|
15 |
#define SHR3 (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5)) |
16 |
#define CONG (jcong=69069*jcong+1234567) |
17 |
#define KISS ((MWC^CONG)+SHR3)
|
18 |
|
19 |
#define CONGfp CONG * 2.328306435454494e-10f |
20 |
#define MWCfp MWC * 2.328306435454494e-10f |
21 |
#define KISSfp KISS * 2.328306435454494e-10f |
22 |
|
23 |
#define ITERATIONS 1000000000 |
24 |
|
25 |
#ifdef LONG
|
26 |
#define LENGTH long long |
27 |
#else
|
28 |
#define LENGTH int |
29 |
#endif
|
30 |
|
31 |
LENGTH MainLoopGlobal(LENGTH iterations,unsigned int seed_w,unsigned int seed_z) |
32 |
{ |
33 |
unsigned int z=seed_z; |
34 |
unsigned int w=seed_w; |
35 |
|
36 |
LENGTH total=0;
|
37 |
|
38 |
for (LENGTH i=0;i<iterations;i++) { |
39 |
|
40 |
float x=MWCfp ;
|
41 |
float y=MWCfp ;
|
42 |
|
43 |
// Matching test
|
44 |
|
45 |
#ifdef IFSQRT
|
46 |
if ( sqrt(x*x+y*y) < 1.0f ) { |
47 |
total+=1;
|
48 |
} |
49 |
#elif IFWOSQRT
|
50 |
if ( (x*x+y*y) < 1.0f ) { |
51 |
total+=1;
|
52 |
} |
53 |
#else
|
54 |
int inside=((x*x+y*y) < 1.0f) ? 1:0; |
55 |
total+=inside; |
56 |
#endif
|
57 |
|
58 |
} |
59 |
|
60 |
return(total);
|
61 |
|
62 |
} |
63 |
|
64 |
int main(int argc, char *argv[]) { |
65 |
|
66 |
unsigned int seed_w=10,seed_z=10; |
67 |
LENGTH iterations=ITERATIONS; |
68 |
|
69 |
if (argc > 1) { |
70 |
iterations=(LENGTH)atoll(argv[1]);
|
71 |
} |
72 |
else {
|
73 |
printf("\n\tPi : Estimate Pi with Monte Carlo exploration\n\n\t\t#1 : number of iterations (default 1 billion)\n\n");
|
74 |
} |
75 |
|
76 |
printf ("\n\tInformation about architecture:\n\n");
|
77 |
|
78 |
printf ("\tSizeof int = %lld bytes.\n", (long long)sizeof(int)); |
79 |
printf ("\tSizeof long = %lld bytes.\n", (long long)sizeof(long)); |
80 |
printf ("\tSizeof long long = %lld bytes.\n\n", (long long)sizeof(long long)); |
81 |
|
82 |
printf ("\tMax int = %u\n", INT_MAX);
|
83 |
printf ("\tMax long = %ld\n", LONG_MAX);
|
84 |
printf ("\tMax long long = %lld\n\n", LLONG_MAX);
|
85 |
|
86 |
float pi=(float)MainLoopGlobal(iterations,seed_w,seed_z)/(float)iterations*4; |
87 |
|
88 |
printf("\tPi=%.40f\n\twith error %.40f\n\twith %lld iterations\n\n",pi,
|
89 |
fabs(pi-4*atan(1))/pi,(long long)iterations); |
90 |
|
91 |
} |