Statistiques
| Révision :

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

Historique | Voir | Annoter | Télécharger (1,71 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 CONGfp CONG * 2.328306435454494e-10f
19
#define MWCfp MWC * 2.328306435454494e-10f
20
#define KISSfp KISS * 2.328306435454494e-10f
21

    
22
#define ITERATIONS 1000000000
23

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

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

    
35
   unsigned  long total=0;
36

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

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

    
42
      // Matching test
43

    
44
#ifdef IFSQRT
45
      if ( sqrt(x*x+y*y) < 1.0f ) {
46
        total+=1;
47
      }
48
#elif IFWOSQRT
49
      if ( (x*x+y*y) < 1.0f ) {
50
        total+=1;
51
      }
52
#else
53
      int inside=((x*x+y*y) < 1.0f) ? 1:0;
54
      total+=inside;
55
#endif
56

    
57
   }
58

    
59
   return(total);
60

    
61
}
62

    
63
int main(int argc, char *argv[]) {
64

    
65
  unsigned int seed_w=10,seed_z=10;
66
  LENGTH iterations=ITERATIONS;
67

    
68
  if (argc > 1) {
69
    iterations=(LENGTH)atol(argv[1]);
70
  }
71
  else {
72
    printf("\n\tPi : Estimate Pi with Monte Carlo exploration\n\n\t\t#1 : number of iterations (default 1 billion)\n\n");
73
  }
74

    
75
  float pi=(float)MainLoopGlobal(iterations,seed_w,seed_z)/(float)iterations*4;
76

    
77
  printf("\tPi=%.40f\n\twith error %.40f\n\twith %lu iterations\n\n",pi,
78
         fabs(pi-4*atan(1))/pi,(unsigned long)iterations);
79
  
80
}