Posted in Javascript onAugust 08, 2013
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; }
JS实现随机数生成算法示例代码
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@