Statistiques
| Révision :

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

Historique | Voir | Annoter | Télécharger (1,92 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 4
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,process=PROCESS;
55
  LENGTH iterations=ITERATIONS;
56
  LENGTH inside[1024],insides=0;
57

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

    
68
#pragma omp parallel for
69
  for (int i=0 ; i<process; i++) {
70
    inside[i]=MainLoopGlobal(iterations/process,seed_w,seed_z);
71
    printf("\tFound %lu for process %i\n",(unsigned long)inside[i],i);
72
  }
73
  printf("\n");
74

    
75
  for (int i=0 ; i<process; i++) {
76
    insides+=inside[i];
77
  }
78
  
79
  float pi=4.*(float)insides/(float)iterations;
80

    
81
  printf("\tPi=%f with error %f and %lu iterations\n\n",pi,
82
         fabs(pi-4*atan(1))/pi,(unsigned long)iterations);
83
  
84
}