Skip to content

Instantly share code, notes, and snippets.

@jinlong
Last active November 24, 2016 08:28
Show Gist options
  • Save jinlong/5633022 to your computer and use it in GitHub Desktop.
Save jinlong/5633022 to your computer and use it in GitHub Desktop.
javascript Math.random() 写了个概率函数(项目中要用,记录一下)
//probability : 0.6(60%)
var getRandom = function(probability){
var probability = probability*10 || 1;
var odds = Math.floor(Math.random()*10);
if(probability === 1){return 1};
if(odds < probability){
return 1;
}else{
return 0;
}
};
/**test case
var arr0 = [], arr1 = [];
var a;
for(var i=0; i< 10000; i++){
a = getRandom(0.6);
if(a == 1){
arr1.push(a);
}else{
arr0.push(a);
}
}
console.log("arr0 : "+ arr0.length);
console.log("arr1 : "+ arr1.length);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment