JavaScript: How To Code a Heads/Tails With Specific Probability Chance Percentage?

£可爱£侵袭症+ 提交于 2021-02-05 12:18:50

问题


I've implemented the function:

 function coinFlip() {
      return(Math.floor(Math.random()*2) === 0) ? 'Heads' : 'Tails';
 }

And it's all working fine (I already tested it).

My problem is, how do I make this function so that the probability of getting 'Heads' is 30% while the probability of getting 'Tails' is 70%?

Thanks in advance


回答1:


function coinFlip() {
      return(Math.random() < 0.3) ? 'Heads' : 'Tails';
 }



回答2:


If one of three toss coin is head it doesn't mean that in 10 toss, there will be 3 heads.. Here is your code with 500 toss (just change the number)

    function coinFlip() {
          return(Math.random() < 0.3) ? 'Heads' : 'Tails'; //ofc 0.3 is 30% (3/10)
    }

 var howManyTimes=500;
 var countHeads=0; 
 for (var i=0; i<howManyTimes;i++){
     if (coinFlip()==='Heads'){
       countHeads++;
     }
 }
 alert("Heads appear "+(countHeads/howManyTimes)*100+"% of the time");

"how to solve a specific percentage problem"

You can't, this is how probability works



来源:https://stackoverflow.com/questions/38175472/javascript-how-to-code-a-heads-tails-with-specific-probability-chance-percentag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!