将随机整数转换为 short 会给出均匀分布吗?
Does casting random integers to short give a uniform distribution?
正如标题所解释的那样,我希望生成一系列随机空值。因为没有 Random.nextShort() 函数,做我想做的最简单的方法似乎是将整数转换为短整数,使用:
Random rand = new Random(int seed);
(short) rand.nextInt()
但是,我不完全理解这种转换是如何进行的,因此我不能确定生成的短值是否仍然是随机的。是这样吗?提前致谢。
数字仍然是随机的,但是您可能会遇到此数字的不同 max/min 值的问题,有关详细信息,请查看此处的第一个答案 here
我认为这行不通,因为 int
比 short
大很多。
只需取一个随机的float
或double
(值在[-1;1]之间)并乘以一个short的最大值:
short i= (short) rand.nextFloat() * Short.MAX_VALUE;
int 的简短转换通过按位截断工作。只要整数是随机分布的,短值也应该是-是的。
来自 Java 语言规范 5.1.3:
A narrowing conversion of a signed integer to an integral type T
simply discards all but the n lowest order bits, where n is the number
of bits used to represent type T.
int
有 32 位,short
有 16 位。本质上,转换与加(或减)65536(即 2 的 16 次方)相同,直到值在short
表示的范围。因此,正好有 65536 个 int
值映射到每个可能的 short
值。
一个避免错误的好方法是:
Random rand = new Random(int seed);
short s = (short) rand.nextInt(Short.MAX_VALUE + 1);
如果你还需要负短路:
short s = (short) rand.nextInt(Short.MAX_VALUE - Short.MIN_VALUE + 1) + Short.MIN_VALUE;
最快的解决方案:
short s = (short) random.nextInt(1 << 16); // any short
short s = (short) random.nextInt(1 << 15); // any non-negative short
规范的方法是 short result = (short)(rand.nextInt(Short.MAX_VALUE-Short.MIN_VALUE+1) + Short.MIN_VALUE)
。这样做的原因是您想要一个范围跨越 Short.MAX_VALUE-Short.MIN_VALUE+1
个值并从 Short.MIN_VALUE
.
开始的数字
简单的截断可能就足够了 short
(如果速度对您很重要,它可能也更快),但这种方法适用于任何范围。
假设您想要一个介于 -5
和 12
(包括两者)之间的随机数,然后您将调用 rand.nextInt(12-(-5)+1)+(-5)
,或者如果您简化所有计算:rand.nextInt(18)-5
.
正如标题所解释的那样,我希望生成一系列随机空值。因为没有 Random.nextShort() 函数,做我想做的最简单的方法似乎是将整数转换为短整数,使用:
Random rand = new Random(int seed);
(short) rand.nextInt()
但是,我不完全理解这种转换是如何进行的,因此我不能确定生成的短值是否仍然是随机的。是这样吗?提前致谢。
数字仍然是随机的,但是您可能会遇到此数字的不同 max/min 值的问题,有关详细信息,请查看此处的第一个答案 here
我认为这行不通,因为 int
比 short
大很多。
只需取一个随机的float
或double
(值在[-1;1]之间)并乘以一个short的最大值:
short i= (short) rand.nextFloat() * Short.MAX_VALUE;
int 的简短转换通过按位截断工作。只要整数是随机分布的,短值也应该是-是的。
来自 Java 语言规范 5.1.3:
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.
int
有 32 位,short
有 16 位。本质上,转换与加(或减)65536(即 2 的 16 次方)相同,直到值在short
表示的范围。因此,正好有 65536 个 int
值映射到每个可能的 short
值。
一个避免错误的好方法是:
Random rand = new Random(int seed);
short s = (short) rand.nextInt(Short.MAX_VALUE + 1);
如果你还需要负短路:
short s = (short) rand.nextInt(Short.MAX_VALUE - Short.MIN_VALUE + 1) + Short.MIN_VALUE;
最快的解决方案:
short s = (short) random.nextInt(1 << 16); // any short
short s = (short) random.nextInt(1 << 15); // any non-negative short
规范的方法是 short result = (short)(rand.nextInt(Short.MAX_VALUE-Short.MIN_VALUE+1) + Short.MIN_VALUE)
。这样做的原因是您想要一个范围跨越 Short.MAX_VALUE-Short.MIN_VALUE+1
个值并从 Short.MIN_VALUE
.
简单的截断可能就足够了 short
(如果速度对您很重要,它可能也更快),但这种方法适用于任何范围。
假设您想要一个介于 -5
和 12
(包括两者)之间的随机数,然后您将调用 rand.nextInt(12-(-5)+1)+(-5)
,或者如果您简化所有计算:rand.nextInt(18)-5
.