Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
merging branch 5018:5083 into trunk
[simgrid.git] / src / surf / random_mgr.c
1
2 #include "surf/random_mgr.h"
3 #include "xbt/sysdep.h"
4
5 static double custom_random(int generator){
6    switch(generator) {
7       case DRAND48: return drand48(); break;
8       case RAND: return (double)rand()/RAND_MAX; break;
9       default: return drand48();
10    }
11 }
12
13 /* Generate numbers between min and max with a given mean and standard deviation */
14 float random_generate(random_data_t random){  
15   float x1, x2, w, y;
16   
17   if (random == NULL) return 0.0f;  
18
19   do {
20     /* 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.
21        It is good for speed because it does not call math functions many times. Another way would be to simply:
22          y1 = sqrt( - 2 * log(x1) ) * cos( 2 * pi * x2 )
23     */ 
24     do {
25       x1 = 2.0 * custom_random(random->generator) - 1.0;
26       x2 = 2.0 * custom_random(random->generator) - 1.0;
27       w = x1 * x1 + x2 * x2;
28     } while ( w >= 1.0 );
29
30     w = sqrt( (-2.0 * log( w ) ) / w );
31     y = x1 * w;
32
33     /* Multiply the Box-Muller value by the standard deviation and add the mean */
34     y = y * random->stdDeviation + random->mean;
35   } while (!(random->min <= y && y <= random->max));
36
37   return y;
38 }
39
40 random_data_t random_new(int generator, int min, int max, int mean, int stdDeviation){
41   random_data_t random = xbt_new0(s_random_data_t, 1);
42   random->generator = generator;
43   random->min = min;
44   random->max = max;
45   random->mean = mean;
46   random->stdDeviation = stdDeviation;
47   return random;
48 }
49