在java中生成0和无穷大之间的随机双精度

时间:2015-11-12 22:07:13

标签: java random nan infinity

我有这段代码

我尝试向该方法发送随机双倍"有趣"

BL是双等于1

   double inf=Double.POSITIVE_INFINITY;
   double rand=inf*R.nextDouble();
   double myrand=fun(rand)*BL;
   mylist.get(i).set_speed(myrand);

这是"有趣"方法

double fun(double v)
{
   return ((pow(A,K)*exp((-1)*A*v)*pow(v,K-1))/(fact(K-1)));
}

但速度参数的输出始终为NaN

4 个答案:

答案 0 :(得分:2)

据我所知,无限远是无法达到的。试试这个

double rand = R.nextDouble(Double.MAX_VALUE- 1);

这将在0和双重

的最大值之间创建一个随机双精度数

答案 1 :(得分:1)

尝试将此行inf*R.nextDouble();更改为Double.MAX_VALUE * R.nextDouble();如果您还需要不时获取Double.POSITIVE_INFINITY,则必须实施额外的if块并随机返回Double.POSITIVE_INFINITY在某些情况下。

答案 2 :(得分:1)

要获得带有正号的双精度值,大于或等于0.0且小于Double.MAX_VALUE:

double r = Math.random()*Double.MAX_VALUE

然后只需将结果传递给您的函数。

答案 3 :(得分:0)

您不能获得0到无穷大之间的数字。

因为如果可以,您将得到一个无穷大的数字。

1。但是您可以得到一个最大值如下的随机数:

int random(int max)
{
    return (int) (Math.random() * max);
}

2。最少数量:

int random(int min, int max)
{
    int range = (max - min) + 1;
    return (int) (Math.random() * range) + min;
}

3。如果您不需要小数,请输入以下内容:

int random(int min, int max)
{
    int range = (max - min) + 1;
    return (int) Math.round((Math.random() * range) + min);
}

否则,如果要向下或向上四舍五入:

//round down
(int) Math.floor((Math.random() * range) + min);

//round up
(int) Math.ceil((Math.random() * range) + min);

留言:

//between 500 1000 (function 2 or 3)
JOptionPane.showMessageDialog(null, random(500, 1000));

//or just maximal: 1000 (function 1)
JOptionPane.showMessageDialog(null, random(1000));

希望它会有所帮助:)