Generating Random Doubles in Java [duplicate]

2019-07-05 18:24发布

问题:

This question already has an answer here:

  • Generate a random double in a range 5 answers

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



标签: java double