随机长度始终是最小值

时间:2015-07-02 22:22:22

标签: java random long-integer

我编写了一个函数来生成Long.MIN_VALUE和Long.MAX_VALUE之间的随机长值,但它总是返回Long.MIN_VALUE,为什么?

public static long randomLong() {
    return (long) (Math.random()*(Long.MAX_VALUE-Long.MIN_VALUE)+Long.MIN_VALUE);
}

感谢您帮助我

2 个答案:

答案 0 :(得分:2)

问题是你的长期价值已经溢出。由于Long.MIN_VALUE对于有符号长整数为负,因此Long.MAX_VALUE-Long.MIN_VALUE大于Long.MAX_VALUE,因此在中间计算期间不适合长整数。

请尝试使用nextLong:

public static long randomLong() {
    Random ran = new Random();
    return ran.nextLong();
}

答案 1 :(得分:2)

由于溢出,Long.MAX_VALUE - Long.MIN_VALUE的结果为-1。该值乘以Math.random()0.0包含和1.0排除值之间的值。它是doubleLong.MIN_VALUE被添加到-1.00.0之间的值,结果仍为Long.MIN_VALUE。与double相比,Long.MIN_VALUE不够精确,无法添加如此之小的内容,因此结果为Long.MIN_VALUE double

要检索均匀分布的随机long,请使用Random类及其method nextLong()

// This Random object can be stored in the class for reuse
Random rnd = new Random();

然后:

return rnd.nextLong();