There are many methods to implement the random number generation algorithm in JS. This article introduces a good method. The Code is as follows. If you are interested, you can refer to it and hope to help you. 1:
The Code is as follows:
Var MT = [];
Var index = 0;
Function initialize_generator (seed ){
MT [0] = seed;
For (var I = 1; I <624; I ++ ){
MT [I] = 0 xffffffff & (0x6c078965 * (MT [I-1] ^ (MT [I-1]> 30) + I );
}
}
Function generate_numbers (){
For (var I = 0; I <624; I ++ ){
Var y = (MT [I] & 0x80000000) + (MT [(I + 1) % 624] & 0x7fffffff );
MT [I] = MT [(I + 397) % 624] ^ (y> 1 );
If (y % 2! = 0 ){
MT [I] ^ = 0x9908b0df;
}
}
}
Function extract_number (){
If (index = 0 ){
Generate_numbers ();
}
Var y = MT [index];
Y ^ = (y> 11 );
Y ^ = (y <7) & 0x9d2c5680 );
Y ^ = (y <15) & 0xefc60000 );
Y ^ = (y> 18 );
Index = (index + 1) % 624;
Return y;
}
Function mt_rand (min, max ){
Return extract_number () % (max-min + 1) + min;
}
Function test (){
Initialize_generator (new Date (). getTime ());
Var test = [0, 0];
For (var I = 0; I <100000; I ++ ){
Test [mt_rand (0, 1)] ++;
}
Return test;
}
2:
The Code is as follows:
Var random = function (t1, t2, t3) {// t1 is the lower limit, t2 is the upper limit, and t3 is the decimal place to be retained
Function isNum (n ){
Return/^ \ d + $/. test (n );
}
If (! T1 | (! IsNum (t1) {t1 = 0 ;}
If (! T2 | (! IsNum (t2) {t2 = 1 ;}
If (! T3 | (! IsNum (t3) {t3 = 0 ;}
T3 = t3> 15? 15: t3; // the decimal place cannot exceed 15 digits
Var ra = Math. random () * (t2-t1) + t1, du = Math. pow (10, t3 );
Ra = Math. round (ra * du)/du;
Return ra;
}