1:
復制代碼 代碼如下:
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] >> 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:
復制代碼 代碼如下:
var random=function(t1,t2,t3){//t1為下限,t2為上限,t3為需要保留的小數位
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; // 小數位不能大於15位
var ra = Math.random() * (t2-t1)+t1,du=Math.pow(10,t3);
ra = Math.round(ra * du)/du;
return ra;
}