Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Do connect all log channel manually to parent using XBT_LOG_CONNECT() too, so that...
[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(int generator){
14    switch(generator) {
15       
16         case DRAND48:return drand48();  
17         case RAND: return (double)rand()/RAND_MAX; 
18    default: return drand48();
19    }
20 }
21
22 /* Generate numbers between min and max with a given mean and standard deviation */
23 float random_generate(random_data_t random){  
24   float x1, x2, w, y;
25   
26   if (random == NULL) return 0.0f;  
27
28   do {
29     /* 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.
30        It is good for speed because it does not call math functions many times. Another way would be to simply:
31          y1 = sqrt( - 2 * log(x1) ) * cos( 2 * pi * x2 )
32     */ 
33     do {
34       x1 = 2.0 * custom_random(random->generator) - 1.0;
35       x2 = 2.0 * custom_random(random->generator) - 1.0;
36       w = x1 * x1 + x2 * x2;
37     } while ( w >= 1.0 );
38
39     w = sqrt( (-2.0 * log( w ) ) / w );
40     y = x1 * w;
41
42     /* Multiply the Box-Muller value by the standard deviation and add the mean */
43     y = y * random->stdDeviation + random->mean;
44   } while (!(random->min <= y && y <= random->max));
45
46   return y;
47 }
48
49 random_data_t random_new(int generator, int min, int max, int mean, int stdDeviation){
50   random_data_t random = xbt_new0(s_random_data_t, 1);
51   random->generator = generator;
52   random->min = min;
53   random->max = max;
54   random->mean = mean;
55   random->stdDeviation = stdDeviation;
56   return random;
57 }
58