3

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?

cvoep28
  • 423
  • 5
  • 9
  • 21

4 Answers4

6

Try this:

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

Note: it should be 20.0 (not 21.0)

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
  • Thank you! Just curious though, why should it be 20 instead of 21? Should it be 20 in the int example also? – cvoep28 Feb 24 '13 at 19:32
  • Because otherwise the minimum value is `-10 + 0.0*20.0` (-10.0) and the maximum is `-10 + 1.0*21.0` (11.0)... – vikingsteve Feb 24 '13 at 19:33
  • And the int example should indeed be `nextInt(21)` since the `Random` doc for this method says that nextInt returns an int *value between 0 (inclusive) and the specified value (exclusive)*. Are you happy with this answer? – vikingsteve Feb 24 '13 at 19:39
  • This will never return 10 since `nextDouble()` can't return 1. `-10.0 + 0.999... * 20.0 != 10` – Pshemo Feb 24 '13 at 19:45
3

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);
}
Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
0

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();
Dennis
  • 32,200
  • 11
  • 64
  • 79
0

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

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

API reference

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110