JS implementation of random number generation algorithm sample code _javascript tips

Source: Internet
Author: User
1:
Copy Code code as follows:

var MT = [];
var index = 0;
function Initialize_generator (seed) {
Mt[0] = seed;
for (var i = 1; i < 624; i++) {
Mt[i] = 0xFFFFFFFF & (0x6c078965 * (mt[i-1) ^ (mt[i-1] >>)) + 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 <<) & 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:
Copy Code code as follows:

The Var random=function (T1,T2,T3) {//t1 is the lower limit, the T2 is the upper limit, and the T3 is the decimal place that needs to be reserved
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; Decimal places cannot be greater than 15 bits
var ra = math.random () * (T2-T1) +t1,du=math.pow (10,T3);
RA = Math.Round (ra * du)/du;
return RA;
}

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.