Statistiques
| Révision :

root / Pi / C / Simple / Pi.c @ 8

Historique | Voir | Annoter | Télécharger (1,5 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

    
10
// Marsaglia RNG very simple implementation
11
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
12
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
13
#define MWC   (znew+wnew)
14
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
15
#define CONG  (jcong=69069*jcong+1234567)
16
#define KISS  ((MWC^CONG)+SHR3)
17

    
18
#define MWCfp MWC * 2.328306435454494e-10f
19
#define KISSfp KISS * 2.328306435454494e-10f
20

    
21
#define ITERATIONS 1000000000
22

    
23
#ifdef LONG
24
#define LENGTH unsigned long
25
#else
26
#define LENGTH unsigned int
27
#endif
28

    
29
LENGTH MainLoopGlobal(LENGTH iterations,unsigned int seed_w,unsigned int seed_z)
30
{
31
   unsigned int z=seed_z;
32
   unsigned int w=seed_w;
33

    
34
   unsigned  long total=0;
35

    
36
   for (LENGTH i=0;i<iterations;i++) {
37

    
38
      float x=MWCfp ;
39
      float y=MWCfp ;
40

    
41
      // Matching test
42
      int inside=((x*x+y*y) < 1.0f) ? 1:0;
43
      total+=inside;
44
   }
45

    
46
   return(total);
47

    
48
}
49

    
50
int main(int argc, char *argv[]) {
51

    
52
  unsigned int seed_w=10,seed_z=10;
53
  LENGTH iterations=ITERATIONS;
54

    
55
  if (argc > 1) {
56
    iterations=(LENGTH)atol(argv[1]);
57
  }
58
  else {
59
    printf("\n\tPi : Estimate Pi with Monte Carlo exploration\n\n\t\t#1 : number of iterations (default 1 billion)\n\n");
60
  }
61

    
62
  float pi=(float)MainLoopGlobal(iterations,seed_w,seed_z)/(float)iterations*4;
63

    
64
  printf("\tPi=%f with error %f and %lu iterations\n\n",pi,
65
         fabs(pi-4*atan(1))/pi,(unsigned long)iterations);
66
  
67
}