2

为了理解 java.util.random 的工作原理,我写了一段简单的代码来模拟 java 随机函数,并比较了 java 随机函数和我的函数的结果。然而,结果是不同的。这意味着要么我犯了一些错误,要么我误解了这个概念。

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);
  }   

}

这是结果的屏幕截图: 结果

n1 不等于 v1。请告诉我我犯了什么错误?谢谢你。

4

1 回答 1

0

好问题!随机生成器毕竟不是随机生成器!您的生成与 Random 之间的唯一区别是您返回long,而 Random 将其强制转换为int

以下更改将修复它:

public static void main(String args[]){
     long multiplier = 0x5DEECE66DL;

    long addend = 0xBL;

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

    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);
    int v1 = (int)(seed1 >>> 16);
    System.out.println("v1: " + v1);

    long seed2 = ((seed1 * multiplier + addend) & mask);
    System.out.println("seed2: " + seed2);
    int v2 = (int)(seed2 >>> 16);
    System.out.println("v2: " + v2);
}
于 2017-11-10T19:55:37.403 回答