【问题标题】:generate short random number in java?在java中生成短随机数?
【发布时间】:2012-04-28 15:53:09
【问题描述】:

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

【问题讨论】:

  • 你需要负数吗?
  • 不,我不需要只从 0 到最大短的负数

标签: java random short


【解决方案1】:

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

编辑

其实做个快速测试,得到的分布似乎也是均匀分布的。

【讨论】:

  • 如果生成的数字大于短期持有的数字怎么办?
  • 只保留最后四位,但不会产生溢出。
  • 但它会改变生成的随机数的微调均匀性吗?
  • 所有最低 16 位都同样可能。演员表之后不会比之前有更多的偏见。
【解决方案2】:

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

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

+1 是因为该方法返回的数字不超过指定的数字(不包括)。见here

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

【讨论】:

  • 但是加1就不能生成0了?
  • @Tudor,+1 被添加到 Short.MAX_VALUE,而不是 nextInt 的结果,因此它会生成一个介于 0 和 Short.MAX_VALUE 之间的数字。
  • 这将产生非负的short 值。
  • @PeterLawrey,这是 OP 要求的 :)
  • @luketorjussen 好的,我知道发生了什么。按照惯例,将方法称为 .nextInteger(int top) 称为 .nextInteger()。但是没有参数的 Random.nextInteger() 给出正数和负数,而 Random.nextInteger(top) 只给出正数。我认为为以后阅读本文的其他人留下明确的信息很有价值。
【解决方案3】:

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

你为什么不做一个

Random.nextInt(65536) - 32768

并将结果转换为 short 变量?

【讨论】:

  • 我猜它并为您编写了它,以便您延长键盘的使用寿命。
【解决方案4】:

只需像这样生成一个 int:

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

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

【讨论】:

  • 这将生成非负短值,除了 Short.MAX_VALUE
【解决方案5】:

可以产生所有可能的短值的最有效的解决方案是做任何一个。

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

甚至更快

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-19
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2013-10-11
    • 2015-01-28
    相关资源
    最近更新 更多