-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRandom.js
101 lines (91 loc) · 2.95 KB
/
Random.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Owner: [email protected]
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
define(function(require, exports, module) {
var RAND = Math.random;
function _randomFloat(min,max) {
return min + RAND() * (max - min);
}
function _randomInteger(min,max) {
return (min + RAND() * (max - min + 1)) >> 0;
}
/**
* Very simple uniform random number generator library wrapping Math.random().
*
* @class Random
* @static
*/
var Random = {};
/**
* Get single random integer between min and max (inclusive), or array
* of size dim if specified.
*
* @method integer
*
* @param {Number} min lower bound, default 0
* @param {Number} max upper bound, default 1
* @param {Number} dim (optional) dimension of output array, if specified
* @return {number | array<number>} random integer, or optionally, an array of random integers
*/
Random.integer = function integer(min,max,dim) {
min = (min !== undefined) ? min : 0;
max = (max !== undefined) ? max : 1;
if (dim !== undefined) {
var result = [];
for (var i = 0; i < dim; i++) result.push(_randomInteger(min,max));
return result;
}
else return _randomInteger(min,max);
};
/**
* Get single random float between min and max (inclusive), or array
* of size dim if specified
*
* @method range
*
* @param {Number} min lower bound, default 0
* @param {Number} max upper bound, default 1
* @param {Number} [dim] dimension of output array, if specified
* @return {Number} random float, or optionally an array
*/
Random.range = function range(min,max,dim) {
min = (min !== undefined) ? min : 0;
max = (max !== undefined) ? max : 1;
if (dim !== undefined) {
var result = [];
for (var i = 0; i < dim; i++) result.push(_randomFloat(min,max));
return result;
}
else return _randomFloat(min,max);
};
/**
* Return random number among the set {-1 ,1}
*
* @method sign
*
* @param {Number} prob probability of returning 1, default 0.5
* @return {Number} random sign (-1 or 1)
*/
Random.sign = function sign(prob) {
prob = (prob !== undefined) ? prob : 0.5;
return (RAND() < prob) ? 1 : -1;
};
/**
* Return random boolean value, true or false.
*
* @method bool
*
* @param {Number} prob probability of returning true, default 0.5
* @return {Boolean} random boolean
*/
Random.bool = function bool(prob) {
prob = (prob !== undefined) ? prob : 0.5;
return RAND() < prob;
};
module.exports = Random;
});