Monday, 20 April 2015

Difference between new Random() and new Random(long seed) constructor behavior

Once again encountered with an interesting thing which I think need to be shared. This is regarding java.util.Random class to generate random numbers in code base and why 2 different constructors provided in Random class, what behavioral changes we are going to achieve using below 2 constructor:
1. new Random();
2. new Random(long seed); 

So we will start our discussion with code examples which covers above constructors.

Example 1 using new Random() constructor:

 import java.util.Random;  
 public class Example7 {  
      public static void main(String[] args) {  
           Random rand = new Random(); //Random instance without seed  
           for(int i=0; i<10; i++){  
                int randomNumber = rand.nextInt(2);  
                System.out.print(randomNumber+", ");  
           }  
      }  
 }  

Output:
 1, 0, 0, 1, 1, 0, 1, 1, 0, 1,   

(Please note output varies from system to system and execution to execution)

Example 2 using new Random(long seed):


 import java.util.Random;  
 public class Example7 {  
      public static void main(String[] args) {  
           Random rand = new Random(2); //Random instance with seed  
           for(int i=0; i<10; i++){  
                int randomNumber = rand.nextInt(2);  
                System.out.print(randomNumber+", ");  
           }  
      }  
 }  

Output:

 1, 0, 1, 0, 0, 1, 1, 0, 1, 1,   

Now with example 2 you will see that you will get same set of result irrespective of how many time you execute example 2.

But at the same time with example 1 where we used new Random() constructor we will get different set of number on different executions.

Till this we can say that definitely it is "seed" parameter which is responsible for giving same set of random numbers every time.

Time to dig to down to "long seed" parameter to understand the behaviour.

If you check the implementation of default constructor of Random class it uses seed value which will be different for every Random class object creation, where as for parametrized constructor of Random, seed value would be same for each object creation with same seed value.

So no matter how many random objects you create with same seed value, there sequence would be same. Also above statement is true for individual execution also.

If you want go to further into deep, better place would be to check code under Random class. It uses "linear congruential pseudo random number generator" to produce random number..to be honest still trying to understand the algorithm behind it :-)

That's all from my end on Random class. Let me know if you can add something more into it, definitely I am looking forward to update the post.

No comments:

Post a Comment