-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom.js
More file actions
74 lines (61 loc) · 1.4 KB
/
random.js
File metadata and controls
74 lines (61 loc) · 1.4 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* Non-uniform random number distributions */
var gaussian_z0 = null;
// generates a random number
// according to a normal distribution
function gaussian() {
if(gaussian_z0 != null) {
ret = gaussian_z0;
gaussian_z0 = null;
return ret;
} else {
var u1 = random();
var u2 = random();
var r = Math.sqrt(-2 * Math.log(u1));
var theta = 2 * Math.PI * u2;
z0 = r * Math.cos(theta);
var z1 = r * Math.sin(theta);
return z1;
}
};
// generates a random number
// using a custom distribution
// options:
// LINEAR: P(x) = x
// EXPONENTIAL: P(x) = x^2
// defaults to linear
function montecarlo(option) {
var r1, r2, probability;
while(true) {
r1 = random();
probability;
switch(option.toLowerCase()) {
case "linear":
probability = r1;
break;
case "exponential":
probability = Math.pow(r1, 2);
break;
default:
probability = r1;
}
r2 = random();
if(r2 < probability) {
return r1;
}
}
};
// map a number from one range to another range
function map(x, in_min, in_max, out_min, out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
// returns a random number between 0 and 1
// TODO_LONGTERM: implement different random number generators
function random0to1() {
return Math.random();
};
function random0toMax(max) {
return Math.random() * max;
};
function randomMintoMax(min, max) {
return Math.random() * (max - min) + min;
};