Math.Random在Java中如何生成随机数

huangapple go评论67阅读模式
英文:

How does Math.Random in Java create random numbers

问题

我可以帮您翻译以下内容:

"I was wandering how I can create my own random number generator for reverse engineering mc seeds by setting starting conditions such as time .thank you in advance."

我在想如何创建自己的随机数生成器,以便通过设置起始条件如时间来进行反向工程MC种子。提前谢谢。

英文:

I was wandering how I can create my own random number generator for reverse engineering mc seeds by setting starting conditions such as time .thank you in advance.

答案1

得分: 1

  1. Math.random 调用了一个类型为 Random 的对象。来源

  2. 调用了 nextDouble来源

  3. nextDouble 的实现如下:

public double nextDouble() {
   return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
}

来源

DOUBLE_UNIT 是 private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)。来源

  1. next 的实现如下:
protected int next(int bits) {
    long oldseed, nextseed;
    AtomicLong seed = this.seed;
    do {
        oldseed = seed.get();
        nextseed = (oldseed * multiplier + addend) & mask;
    } while (!seed.compareAndSet(oldseed, nextseed));
    return (int)(nextseed >>> (48 - bits));
}

来源

正如您所看到的,这是一个线性同余伪随机数生成器。
1: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/Math.java#L809
2: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/Random.java#L531
3: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/Random.java#L92
4: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/Random.java#L198

英文:
  1. Math.random calls an object of type Random, Source

  2. nextDouble is called, Source

  3. nextDouble is implemented like this:

public double nextDouble() {
   return (((long)(next(26)) &lt;&lt; 27) + next(27)) * DOUBLE_UNIT;
}

Source

DOUBLE_UNIT is private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53) Source.

  1. next is implemented like this:
protected int next(int bits) {
        long oldseed, nextseed;
        AtomicLong seed = this.seed;
        do {
            oldseed = seed.get();
            nextseed = (oldseed * multiplier + addend) &amp; mask;
        } while (!seed.compareAndSet(oldseed, nextseed));
        return (int)(nextseed &gt;&gt;&gt; (48 - bits));
}

Source

As you can see, it's a
>linear congruential pseudorandom number generator

huangapple
  • 本文由 发表于 2020年8月12日 00:06:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63362098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定