Generating Random Doubles in Java [duplicate]

别等时光非礼了梦想. 提交于 2019-12-10 21:01:32

问题


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?


回答1:


Try this:

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

Note: it should be 20.0 (not 21.0)




回答2:


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



回答3:


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



回答4:


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

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

API reference



来源:https://stackoverflow.com/questions/15055624/generating-random-doubles-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!