root / Pi / C / Simple / Pi_Integer.c @ 26
Historique | Voir | Annoter | Télécharger (1,38 ko)
1 |
//
|
---|---|
2 |
// Estimation of Pi using Monte Carlo exploration process
|
3 |
// gcc -std=c99 -O3 -o Pi Pi.c -lm
|
4 |
//
|
5 |
#include <math.h> |
6 |
#include <stdio.h> |
7 |
#include <stdlib.h> |
8 |
|
9 |
// Marsaglia RNG very simple implementation
|
10 |
#define znew ((z=36969*(z&65535)+(z>>16))<<16) |
11 |
#define wnew ((w=18000*(w&65535)+(w>>16))&65535) |
12 |
#define MWC (znew+wnew)
|
13 |
#define SHR3 (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5)) |
14 |
#define CONG (jcong=69069*jcong+1234567) |
15 |
#define KISS ((MWC^CONG)+SHR3)
|
16 |
|
17 |
#define MWCfp MWC * 2.328306435454494e-10f |
18 |
#define KISSfp KISS * 2.328306435454494e-10f |
19 |
|
20 |
#define ITERATIONS 1000000000 |
21 |
|
22 |
unsigned int MainLoopGlobal(unsigned int iterations,unsigned int seed_w,unsigned int seed_z) |
23 |
{ |
24 |
unsigned int z=seed_z; |
25 |
unsigned int w=seed_w; |
26 |
|
27 |
unsigned int total=0; |
28 |
|
29 |
for (unsigned int i=0;i<iterations;i++) { |
30 |
|
31 |
float x=MWCfp ;
|
32 |
float y=MWCfp ;
|
33 |
|
34 |
// Matching test
|
35 |
int inside=((x*x+y*y) < 1.0f) ? 1:0; |
36 |
total+=inside; |
37 |
} |
38 |
|
39 |
return(total);
|
40 |
|
41 |
} |
42 |
|
43 |
int main(int argc, char *argv[]) { |
44 |
|
45 |
unsigned int seed_w=10,seed_z=10; |
46 |
unsigned int iterations=ITERATIONS; |
47 |
|
48 |
if (argc > 1) { |
49 |
iterations=(unsigned int)atol(argv[1]); |
50 |
} |
51 |
else {
|
52 |
printf("\n\tPi : Estimate Pi with Monte Carlo exploration\n\n\t\t#1 : number of iterations (default 1 billion)\n");
|
53 |
} |
54 |
|
55 |
float pi=(float)MainLoopGlobal(iterations,seed_w,seed_z)/(float)iterations*4; |
56 |
|
57 |
printf("Pi=%f with %u iterations\n",pi,iterations);
|
58 |
|
59 |
} |