Sample Code for using javascript to generate random numbers _ javascript skills

Source: Internet
Author: User
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;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.