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
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
Share Improve this question asked Jul 4, 2016 at 0:17 5120bee5120bee 7092 gold badges16 silver badges38 bronze badges 5- 1 Pick a random number between 0 and 1. If the number is <0.3 it's Heads. Else, it's Tails... – Maria Ines Parnisari Commented Jul 4, 2016 at 0:19
- Okay, but suppose that I do 10 coin flips. I want to print out the results and by logic, 3 of those will be heads and 7 will be tails. How do I implement that? – 5120bee Commented Jul 4, 2016 at 0:21
- it is not a sure thing that 3 of those will be heads and 7 of those will be tails. Over many many repeated experiments, the average will be 3 heads and 7 will tails – derp Commented Jul 4, 2016 at 0:22
- "3 of those will be heads"? Um, no. 3 of those will most likely be heads. Use an array – Maria Ines Parnisari Commented Jul 4, 2016 at 0:22
- I already put them in an array. Like I said, I tested everything out and all is working in order. I just wanted a possible solution for how to solve a specific percentage problem. EDIT: I have my entire code working, I just didn't put it on here since my only problem is getting the correct percentage for the heads/tails result. – 5120bee Commented Jul 4, 2016 at 0:24
2 Answers
Reset to default 6function coinFlip() {
return(Math.random() < 0.3) ? 'Heads' : 'Tails';
}
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745245527a4618394.html
评论列表(0条)