Sunday, October 5, 2014

java.lang.Math.random() and java.util.Random


import java.util.Random;

public class RandomTest {
   
    public static void main(String[] args){
       
        // 1) java.util.Random to generate random number
        Random random = new Random(1000); // 1000 is seed
        for (int i = 0; i<3; i++){
            System.out.println(random.nextInt()); // generates same random number because of seed is fixed
        }
       
        // 2) java.lang.Math.random() to generate random number
        for (int i=0; i<3; i++){
            System.out.println(Math.random()); // random double between 0 and 1, 0 is inclusive
        }
    }

}


OUTPUT:

-1244746321   (same)
1060493871    (same) 
-1826063944   (same)
0.22284876712156954   (different)
0.19407514115469882   (different)
0.2939945031187672     (different)

No comments:

Post a Comment