Statistiques
| Révision :

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

Historique | Voir | Annoter | Télécharger (1,55 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
      int inside=((x*x+y*y) < 1.0f) ? 1:0;
44
      total+=inside;
45
   }
46

    
47
   return(total);
48

    
49
}
50

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

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

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

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

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