java 在java中生成短随机数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10189016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:59:25  来源:igfitidea点击:

generate short random number in java?

javarandomshort

提问by waqas

I want to generate a random number of type short exactly like there is a function for integer type called Random.nextInt(134116). How can I achieve it?

我想生成一个 short 类型的随机数,就像有一个名为 Random.nextInt(134116) 的整数类型函数一样。我怎样才能实现它?

回答by luketorjussen

There is no Random.nextShort()method, so you could use

没有Random.nextShort()方法,所以你可以使用

short s = (short) Random.nextInt(Short.MAX_VALUE + 1);

The +1 is because the method returns a number up to the number specified (exclusive). See here

+1 是因为该方法返回一个数字,直到指定的数字(不包括)。看这里

This will generate numbers from 0 to Short.MAX_VALUE inclusive (negative numbers were not requested by the OP)

这将生成从 0 到 Short.MAX_VALUE 的数字(OP 未请求负数)

回答by Peter Lawrey

The most efficient solution which can produce all possible short values is to do either.

可以产生所有可能的短值的最有效的解决方案是执行任一操作。

short s = (short) random.nextInt(1 << 16); // any short
short s = (short) random.nextInt(1 << 15); // any non-negative short

or even faster

甚至更快

class MyRandom extends Random {
    public short nextShort() {
        return (short) next(16); // give me just 16 bits.
    }
    public short nextNonNegativeShort() {
        return (short) next(15); // give me just 15 bits.
    }
}

short s = myRandom.nextShort();

回答by Skippy Fastol

Java shorts are included in the -32 768 → +32 767 interval.

Java Shorts 包含在 -32 768 → +32 767 区间内。

why wouldn't you perform a

你为什么不表演一个

Random.nextInt(65536) - 32768

and cast the result into a shortvariable ?

并将结果转换为一个变量?

回答by assylias

How about short s = (short) Random.nextInt();? Note that the resulting distribution might have a bias. The Java Language Specification guarantees that this will not result in an Exception, the int will be truncated to fit in a short.

怎么样short s = (short) Random.nextInt();?请注意,结果分布可能存在偏差。Java 语言规范保证这不会导致异常,int 将被截断以适应 short。

EDIT

编辑

Actually doing a quick test, the resulting distribution seems to be uniformly distributed too.

实际上做一个快速测试,结果分布似乎也是均匀分布的。

回答by Tudor

Simply generate an int like:

只需生成一个 int 像:

 short s = (short)Random.nextInt(Short.MAX_VALUE);

The generated intwill be in the value space of short, so it can be cast without data loss.

生成的int将在 的值空间中short,因此可以在不丢失数据的情况下进行转换。