vendredi 10 novembre 2017

how does java.util.random work?

In order to understand how java.util.random works, I wrote a piece of simple code to simulate the java random functions and compared the results of java random function's and my function's. However, the results are different. It means either I made some mistakes or I misunderstood the concept.

import java.util.Random;

public class test2 {
  private static long multiplier = 0x5DEECE66DL;

  private static long addend = 0xBL;

  private static long mask = (1L << 48) - 1;


  public static void main(String args[]){
    long seed = 128856;
    Random random = new Random(seed);
    long n1 = random.nextInt();
    long n2 = random.nextInt();
    long n3 = random.nextInt();

    System.out.println("Results: " + n1 +" "+ n2 +" "+ n3);


    System.out.println("seed: " + seed);
    long seed0 = (seed ^ multiplier) & mask;
    System.out.println("seed0: " + seed0);

    long seed1 = ((seed0 * multiplier + addend) & mask);
    System.out.println("seed1: " + seed1);     
    long v1 = seed1 >>> 16;
    System.out.println("v1: " + v1);

    long seed2 = ((seed1 * multiplier + addend) & mask); 
    System.out.println("seed2: " + seed2);
    long v2 = seed2 >>> 16;
    System.out.println("v2: " + v2);
  }   

}

And here is the screenshot of the result: Result

n1 is not equal to v1. Please tell me what the mistakes I made? Thank you.




Aucun commentaire:

Enregistrer un commentaire