Last active
November 24, 2016 08:28
-
-
Save jinlong/5633022 to your computer and use it in GitHub Desktop.
javascript Math.random() 写了个概率函数(项目中要用,记录一下)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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