daisyDuck
daisyDuck

Reputation: 311

How to count a random output within a loop?

Given is:

var summe = 0;
var i = 1;
while(summe < 4){
    summe += Math.random();
    document.write(i++ + ") " + summe + "<br>");
}

i often is within a range of 6 and 12 additions until the while is fulfilled.

How to count, let´s say, for 1000 times how many times the additions was between 4 and 20?

Upvotes: 2

Views: 100

Answers (1)

scraaappy
scraaappy

Reputation: 2886

Unfortunately, I was skipping classes during the probability courses at school, and I hope for you that you were more assiduous, but finally, your question boils down to:

  • what are the odds of performing the operation less than 4 times? (0 since you expect a result strictly greater than 4, so there will be at least 5 operations),
  • and what are the chances of repeating the operation + 20 times, knowing that at each operation I have a 20% chance to get a result that will allow me to fulfill the condition.

And this independently of the number of tests.

The snippet below will possibly be able to correlate the scholar calculation of probability which you will produce:

var result = [];
var j=0;
for (j;j<1000000;j++){
  var summe = 0;
  var i = 1;
  while(summe < 4){
      summe += Math.random();
   //   document.write(i + ") " + summe + "<br>");
      i++;
  }
  result.push(i);
}


const matchingResult = result.filter(num=>num<=20 && num>4);
// or that can be simplyfied  const matchingResult = result.filter(num=>num<=20);
console.log(matchingResult.length/10000,"%","between 4 and 20");

console.log(result.filter(num=>num>20));

Hope this help!;)

Upvotes: 1

Related Questions