-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandom.js
531 lines (478 loc) · 13 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
"use strict";
(function (root){
//This random generator use MT19937
//Return a random number between [0,1)
var uniform = (function(){
//generate a random seed for Mersenne twister algorithm.
var SEED = Math.random() * Date.now();
var MT = [parseInt(SEED)];
var RAND_MAX = 0x7fffffff;
var index = 0;
//Initialize the generator from the seed
for (var i=1;i<624 ;i++ ){
MT[i] = (1812433253 * (MT[i-1] ^ (MT[i-1] >> 30)) + i) & 0xffffffff;
}
//genarate random number
function msRand(){
if (index === 0){
msRenerate();
}
var y = MT[index];
y = y ^ (y >> 11);
y = y ^ ((y << 7) & 0x9d2c5680);
y = y ^ ((y << 15) & 0xefc60000);
y = y ^ (y >> 18);
index = (index + 1) % 624;
return y;
}
function msRenerate(){
var i,y;
for (i=0;i<624 ;i++ ){
y = (MT[i] & 0x80000000) + (MT[(i+1) % 624] & 0x7fffffff);
MT[i] = MT[(i + 397) % 624] ^ (y >> 1);
if ( y % 2 !== 0){
MT[i] = MT[i] ^ 0x9908b0df;
}
}
}
return function uniform(){
return msRand()/ RAND_MAX;
}
})();
/*
use Math.random function to replace the uniform random generator
*/
function useMathRandom(){
uniform = Math.random.bind(Math);
}
/*
Return random Float number between (start,end).
the defaut value of `start` and `end` is 0 and 1.
randFloat() <--> [0,1)
randFloat(a) <--> [0,a)
randFloat(a,b) <--> [a,b)
*/
function randFloat(start,end){
if (undefined == start){
return uniform();
}
if (undefined == end){
return start * uniform();
}
return start + uniform()*(end-start);
}
function randInt(){
return parseInt(randFloat.apply(null,arguments));
}
function Int32(){
return ~~(0x7fffffff * uniform());
}
function toHex(number){
return number.toString(16);
}
function color(){
return [randInt(0,256),randInt(0,256),randInt(0,256)];
}
function leftpad(str,len,char){
len = len || 4;
char = char || "0";
return new Array(len + 1 - str.length).join(char) + str;
}
function colorHex(){
return "#" + color().map(toHex).map(function (v){
return leftpad(v,2,0);
}).join("");
}
function select(list,fn){
fn = fn || uniform;
var randNum = Math.abs(fn());
if (randNum > 1){
randNum = randNum % 1.0;
}
randNum = Math.floor(randNum * list.length);
return list[randNum];
}
function choice(list){
return select(list);
}
function shuffle(list){
if (typeof list === "string"){
return shuffle(list.split('')).join('');
}
if (Array.isArray(list)){
var array = list.concat();
var len = array.length;
array.forEach(function(v,i){
var idx = randInt(i,len)
array[i] = array[idx]
array[idx] = v
})
return array
}
}
function range(head,tail,step){
var argv = [].slice(arguments);
var head = 0,tail = 0,step = 1,array = [];
switch(argv.length){
case 1:
tail = argv[0];
break;
case 2:
head = argv[0];
tail = argv[1];
break;
case 3:
head = argv[0];
tail = argv[1];
step = argv[2];
break;
}
for (var i=head;i<=tail ;i += step){
array.push(i);
}
return shuffle(array);
}
function uuid(len, radix){
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''),
uuid = [],
radix = radix || chars.length,
i,r;
if (len){
for (i = 0; i < len; i++){
uuid[i] = chars[0|uniform()*radix];
}
}else {
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | uniform()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
function sample(array,num){
var copy = [].map.call(array,function(v){return v;});
num = num || randInt(1,copy.length);
if (num >= copy.length){
return shuffle(copy);
}else {
var arr = [];
while(arr.length<num){
copy=this.shuffle(copy);
arr.push(copy.shift());
}
return arr;
}
}
function Uniform(lower,upper){
return function (){
return lower + uniform()*(upper-lower);
};
}
function Gaussian(mu,sigma){
return function (){
return normal()*Math.sqrt(sigma)+mu;
};
}
function Lognormal(mu,sigma){
var generator = Gaussian(mu,sigma);
return function (){
return Math.exp(generator());
};
}
//Box–Muller transform
var normal = (function (){
var generate = false;
var v1=0.0, v2=0.0, x=0.0;
var uniform = Uniform(-1,1);
return function (){
if (generate){
generate = false;
return v2 * x;
}else {
var s;
do{
v1 = uniform();
v2 = uniform();
s = v1*v1 + v2*v2;
}while(s == 0 || s >= 1);
x = Math.sqrt(-2 * Math.log(s) / s);
generate = true;
return v1 * x;
}
};
})();
function Bernoulli(prob){
var prob = prob;
return function (){
return uniform() < prob;
};
}
//factorial f(N) = N!
var factorial = (function(){
var record = [1,1];
return function (n){
if (!record[n]){
record[n] = n*factorial(n-1);
}
return record[n];
};
})();
function Binomial(up,prob){
var generator = Bernoulli(prob);
return function (){
var x = 0;
for (var i=0;i<up ;i++ ){
if (generator()){
x += 1;
}
}
return x;
};
}
function negativeBinomial(times,prob){
var generator = Bernoulli(prob);
return function (){
var success=0,fail=0;
do{
if (generator()){
success += 1;
}else {
fail += 1;
}
}
while (fail<times);
return success;
};
}
function Cauchy(location,scale){
return function (){
return Math.tan(uniform() * Math.PI) * scale + location;
};
}
function Gumbel(location,scale){
return function (){
return -Math.log(Math.log(1/uniform())) * scale + location;
};
}
function Logistic(location,scale){
return function (){
return -Math.log(1/uniform() - 1) * scale + location;
};
}
/*
Marsaglia and Tsang (2001).
*/
function Gamma(shape,scale){
return function (){
var d = shape - 1 / 3;
var c = 1 / Math.sqrt(9 * d);
do {
do {
var x = gaussian();
var v = Math.pow(c * x + 1, 3);
} while (v <= 0);
var u = uniform();
var x2 = Math.pow(x, 2);
} while (u >= 1 - 0.0331 * x2 * x2 && Math.log(u) >= 0.5 * x2 + d * (1 - v + Math.log(v)));
if (shape < 1) {
return scale * d * v * Math.exp(exponential() / -shape);
} else {
return scale * d * v;
}
};
}
function Chisquared(degree){
return Gamma(degree/2,2);
}
function Poisson(mean){
var c = Math.exp(-mean);
return function (){
var x=0,b=1;
do {
x += 1;
b *= uniform();
}
while(b>=c);
return x;
};
}
function Exponential(lamda){
return function (){
return -Math.log(uniform())/lamda;
};
}
function Geometric(prob){
var temp = Math.log(1-prob);
return function (){
return Math.ceil(Math.log(uniform())/temp) - 1;
};
}
function Weibull(shape,scale){
var temp = -Math.pow(scale,shape);
return function (){
return Math.pow(temp*Math.log(uniform()),1/shape);
};
}
function Rayleigh(scale){
return Weibull(2,scale);
}
function gaussian(mu,sigma){
if (undefined == mu){
mu = 0;
sigma = 1;
}
if (undefined == sigma){
sigma = 1;
}
return Gaussian(mu,sigma)();
}
function lognormal(mu,sigma){
if (undefined == mu){
mu = 0;
sigma = 1;
}
if (undefined == sigma){
sigma = 1;
}
return Lognormal(mu,sigma)();
}
function bernoulli(prob){
if (undefined == prob){
prob = 0.5;
}
return Bernoulli(prob)();
}
function cauchy(location,scale){
if (undefined == location){
location = 0;
scale = 1;
}
if (undefined == scale){
scale = 1;
}
return Cauchy(location,scale)();
}
function gumbel(location,scale){
if (undefined == location){
location = 0;
scale = 1;
}
if (undefined == scale){
scale = 1;
}
return Gumbel(location,scale)();
}
function logistic(location,scale){
if (undefined == location){
location = 0;
scale = 1;
}
if (undefined == scale){
scale = 1;
}
return Logistic(location,scale)();
}
function poisson(mean){
mean = mean || 1;
return Poisson(mean)();
}
function gamma(shape,scale){
if (undefined == shape){
shape = 1;
scale = 1;
}
if (undefined == scale){
scale = 1;
}
return Gamma(shape,scale)();
}
function chisquared(degree){
if (undefined == degree){
degree = 1;
}
return Chisquared(degree)();
}
function exponential(lamda){
lamda = lamda || 1;
return Exponential(lamda)();
}
function geometric(prob){
prob = prob || 0.5;
return Geometric(prob)();
}
function binomial(up,prob){
return Binomial(up,prob)();
}
function weibull(shape,scale){
if (undefined == shape){
shape = 1;
scale = 1;
}
if (undefined == scale){
scale = 1;
}
return Weibull(shape,scale)();
}
var JSrandom = {
useMathRandom:useMathRandom,
randFloat:randFloat,
randInt:randInt,
Int32:Int32,
color:color,
colorHex:colorHex,
uuid:uuid,
select:select,
choice:choice,
sample:sample,
shuffle:shuffle,
Uniform:Uniform,
Gaussian:Gaussian,
Lognormal:Lognormal,
Bernoulli:Bernoulli,
Cauchy:Cauchy,
Gumbel:Gumbel,
Logistic:Logistic,
Poisson:Poisson,
Gamma:Gamma,
Chisquared:Chisquared,
Exponential:Exponential,
Geometric:Geometric,
Binomial:Binomial,
Weibull:Weibull,
Rayleigh:Rayleigh,
uniform:uniform,
gaussian:gaussian,
lognormal:lognormal,
bernoulli:bernoulli,
cauchy:cauchy,
gumbel:gumbel,
logistic:logistic,
poisson:poisson,
gamma:gamma,
chisquared:chisquared,
exponential:exponential,
geometric:geometric,
binomial:binomial,
weibull:weibull
};
if (typeof define === "function" && define.amd) {
define(function () {
return JSrandom;
});
}else if(typeof module !== "undefined" && typeof require === "function") {
module.exports = JSrandom;
}else {
(function () {
var oldGlobal = root.JSrandom;
JSrandom.noConflict = function () {
root.JSrandom = oldGlobal;
return this;
};
})();
root.JSrandom = JSrandom;
}
})(this);