﻿ Javascript 随机数函数 学习之一：产生服从均匀分-JavaScript_网络编程-脚本宝典

Javascript 随机数函数 学习之一：产生服从均匀分

Javascript 随机数函数 学习之一：产生服从均匀分

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive)

Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy.

The Math.random() method returns a random number between the 0 and the 1, not including either 0, or 1.

var count=0;
for(var i=0;i<100000000;i++){
if(Math.random()===0.0){
count++;
}
}
console.log("count:"+count);

var count=0;
for(var i=0;i<100000000;i++){
if(Math.random()===1.0){
count++;
}
}
console.log("count:"+count);

var temp;
var arr=[0,0,0,0,0,0,0,0,0,0];
for(var i=0;i<1000000000;i++){
temp=Math.floor(Math.random()*10+1);
arr[temp]=arr[temp]+1;
}

for (var j = 0; j < arr.length; j++) {
console.log(j + ":" + arr[j]);
}

var temp;
var arr=[0,0,0,0,0,0,0,0,0,0,0,0];
for(var i=0;i<1000000000;i++){
temp=Math.round(Math.random()*10+1);
arr[temp]=arr[temp]+1;
}

for (var j = 0; j < arr.length; j++) {
console.log("得到"+j+"的概率:" + arr[j]/1000000000);
}

function randomColor(){
var rc=function(){
return Math.floor(Math.random()*256);
}
return "rgb("+rc()+","+rc()+","+rc()+")";
}

Tags：

﻿
<