Statistiques
| Révision :

root / Pi / C / OpenMP / Pi_OpenMP.c @ 8

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

    
22
#define ITERATIONS 1000000000
23

    
24
#define PROCESS 8
25

    
26
#ifdef LONG
27
#define LENGTH unsigned long
28
#else
29
#define LENGTH unsigned int
30
#endif
31

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

    
37
   LENGTH total=0;
38

    
39
   for (LENGTH i=0;i<iterations;i++) {
40

    
41
      float x=MWCfp ;
42
      float y=MWCfp ;
43

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

    
49
   return(total);
50
}
51

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

    
54
  unsigned int seed_w=10,seed_z=10;
55
  LENGTH iterations=ITERATIONS;
56
  LENGTH inside[1024],insides=0;
57

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

    
65
#pragma omp parallel for
66
  for (int i=0 ; i<PROCESS; i++) {
67
    inside[i]=MainLoopGlobal(iterations/PROCESS,seed_w,seed_z);
68
    printf("%lu\n",inside[i]);
69
  }
70

    
71
  for (int i=0 ; i<PROCESS; i++) {
72
    insides+=inside[i];
73
  }
74
  
75
  float pi=4.*(float)insides/(float)iterations;
76

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