summaryrefslogtreecommitdiff
path: root/src/main/random.cc
blob: 58987fda785053b2e9210500b1627889c38b113f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
 * random.cc
 *
 *  Created on: May 23, 2011
 *      Author: jakob
 */
#include <math.h>
#include "random.h"

namespace vhc {

namespace random {

void seed(unsigned int s) {
    if (s == 0) {
    	srand(time(0));
    } else {
    	srand(s);
    }
}

double uniform(double a, double b) {
    return a + (rand() / double(RAND_MAX)) * (b - a);
}

double gaussian(double average, double standardDeviation) {
  double v1;
  double v2;
  double s ;

  do {
    v1 = uniform(-1.0, 1.0);
    v2 = uniform(-1.0, 1.0);
    s = v1*v1 + v2*v2;
  } while ((s >= 1.0) or (s == 0.0));

  double x(sqrt(-2.0 * log(s) / s));
  if (uniform(0.0, 1.0) > 0.5)
    x *= v1;
  else
    x *= v2;

  return average + standardDeviation * x;
}

} //random

} //vhc