gpt4 book ai didi

java - 使用随机长整型生成随机 double

转载 作者:行者123 更新时间:2023-12-01 21:30:05 25 4
gpt4 key购买 nike

我正在实现自己的随机数生成器,我使用的算法自然会为我提供一个 nextLong() 方法。但是,使用这个核心方法,我需要实现其他标准方法,例如 nextLong(long)nextInt()nextDouble() > 等等,用 nextLong() 表示。例如:

public long nextLong(long n) {
long bits, val;
do {
bits = (nextLong() << 1) >>> 1;
val = bits % n;
} while (bits - val + n - 1 < 0L);
return val;
}

public int nextInt() {
return (int)nextLong();
}

如何实现nextDouble

最佳答案

不知道自己这样做的目的是什么,但是你可以像内置的 Random 一样这样做。类为 nextDouble() 执行此操作,如 javadoc 中所述:

The method nextDouble is implemented by class Random as if by:

public double nextDouble() {
return (((long)next(26) << 27) + next(27))
/ (double)(1L << 53);
}

因为您没有 int next(int bits)方法,但你确实有一个 nextLong()方法,使用 ((long)next(26) << 27) + next(27)相当于 next(53) 。这是因为 next(int)方法返回 int ,即最大。 32 位。

要从 long 中获取 53 位,您可以选择使用低 53 位或高 53 位:

long low53 = nextLong() & ((1L << 53) - 1);
long high53 = nextLong() >>> (64 - 53);

因此,您的代码将是:

private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
public double nextDouble() {
return (nextLong() >>> (64 - 53)) * DOUBLE_UNIT;
}

DOUBLE_UNIT东西是怎么样Random实际上是在内部完成的,因为乘法比除法更快,例如请参阅Floating point division vs floating point multiplication .

关于java - 使用随机长整型生成随机 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37529005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com