Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Getting rid of network_links.
[simgrid.git] / src / surf / random_mgr.c
1
2 #include "surf/random_mgr.h"
3 #include "xbt/sysdep.h"
4
5 #ifdef WIN32
6 static double drand48(void)
7 {
8    THROW_UNIMPLEMENTED;
9    return -1;
10 }
11 #endif
12
13 static double custom_random(Generator generator, long int *seed){
14    switch(generator) {
15    case DRAND48:
16      return drand48();  
17    case RAND: 
18      return (double)rand_r((unsigned int*)seed)/RAND_MAX; 
19    default: return drand48();
20    }
21 }
22
23 /* Generate numbers between min and max with a given mean and standard deviation */
24 double random_generate(random_data_t random){  
25   double x1, x2, w, y;
26   
27   if (random == NULL) return 0.0f;  
28
29   do {
30     /* Apply the polar form of the Box-Muller Transform to map the two uniform random numbers to a pair of numbers from a normal distribution.
31        It is good for speed because it does not call math functions many times. Another way would be to simply:
32          y1 = sqrt( - 2 * log(x1) ) * cos( 2 * pi * x2 )
33     */ 
34     do {
35       x1 = 2.0 * custom_random(random->generator,&(random->seed)) - 1.0;
36       x2 = 2.0 * custom_random(random->generator,&(random->seed)) - 1.0;
37       w = x1 * x1 + x2 * x2;
38     } while ( w >= 1.0 );
39
40     w = sqrt( (-2.0 * log( w ) ) / w );
41     y = x1 * w;
42
43     /* Multiply the Box-Muller value by the standard deviation and add the mean */
44     y = y * random->stdDeviation + random->mean;
45   } while (!(random->min <= y && y <= random->max));
46
47   return y;
48 }
49
50 random_data_t random_new(Generator generator, long int seed, 
51                          double min, double max, double mean, 
52                          double stdDeviation){
53   random_data_t random = xbt_new0(s_random_data_t, 1);
54   random->generator = generator;
55   random->seed = seed;
56   random->min = min;
57   random->max = max;
58   random->mean = mean;
59   random->stdDeviation = stdDeviation;
60   return random;
61 }
62