samedi 1 décembre 2018

Java random number probability looks wrong

import java.security.SecureRandom;

public class Main {

       public static void main(String[] args) {

       SecureRandom secureRandom = new SecureRandom();
       int sum = 0;

       // generate random number 250 times
       for(int i = 0; i < 250; i++) {

           // generate random number between 1 and 5
           int guess = 1 + secureRandom.nextInt(5);

           // how many times occur number 3 between 1 and 5
           if(guess == 3) {
               sum++;
           }
       }
       System.out.println(sum); // print sum
   }
}

As a result of code above, sum is coming around 50 as expected

import java.security.SecureRandom;

public class Test {

    public static void main(String[] args) {

         SecureRandom random = new SecureRandom();
         int sum = 0;

         // generate random number 250 times
         for(int i = 0; i < 250; i++) {

              int guess1 = 1 + random.nextInt(5); // first random num
              int guess2 = 1 + random.nextInt(5); // second random num

              // if they are equal increase sum by one
              if(guess1 == guess2) {
                   sum++;
              }
         }
         System.out.println(sum); // print sum
     }
 }

In that case sum should not be around 50. According to my calculation it should be 10 but it is also around 50. Can somebody explain why it happens like that ?




Aucun commentaire:

Enregistrer un commentaire