Generating Random Doubles in Java [duplicate]

2019-07-05 17:47发布

This question already has an answer here:

I'm a Java noob trying to generate a random double between -10 and 10 inclusive. I know with ints I would do the following:

Random r = new Random(); 
int i = -10 + r.nextInt(21);

However, with doubles, this doesn't work:

Random r = new Random(); 
double i = -10 + r.nextDouble(21); 

Can someone please explain what to do in the case of doubles?

标签: java double
4条回答
手持菜刀,她持情操
2楼-- · 2019-07-05 18:15

There is no nextDouble(int) method in Random. Use this:

double i = -10.0 + r.nextDouble() * 20.0; 

API reference

查看更多
劳资没心,怎么记你
3楼-- · 2019-07-05 18:18

Try to use this for generate values in given range:

Random random = new Random();
double value = min + (max - min) * random.nextDouble();

Or try to use this:

public double doubleRandomInclusive(double max, double min) {
   double r = Math.random();
   if (r < 0.5) {
      return ((1 - Math.random()) * (max - min) + min);
   }
   return (Math.random() * (max - min) + min);
}
查看更多
We Are One
4楼-- · 2019-07-05 18:26

Try this:

    Random r = new Random(); 
    double d = -10.0 + r.nextDouble() * 20.0; 

Note: it should be 20.0 (not 21.0)

查看更多
狗以群分
5楼-- · 2019-07-05 18:33

Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

nextDouble doesn't take a parameter, you just need to multiply it by whatever your range is. Or more generally:

minimum + (maximum - minimum) * r.nextDouble();
查看更多
登录 后发表回答