Generating a random double number of a certain range in Java

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I have seen posts which explains pretty much this question but they all used integer values and I honestly do not fully understand it hence this question:

I am trying to generate random numbers from the range (-1554900.101) to (52952058699.3098) in java and I was wondering if anyone could explain this to me as I really want to understand it.

My thoughts: will this be a right approach? 1) Generate a random integer number within my specified range 2) Divide the generated number by pi to get float/double random results

Thanks in advance.

Answers

Here s the idea. You want a random number in a range , let s say [-1.1,2.2], to start with a simple example. That range has length 3.3 since 2.2 - (-1.1) = 3.3. Now most "random" functions return a number in the range [0,1), which has length one, so we have to scale our random number into our desired range.

Random random = new Random();
double rand = random.nextDouble();
double scaled = rand * 3.3;

Now our random number has the magnitude we want but we must shift it in the number line to be between the exact values we want. For this step, we just need to add the lower bound of the entire range to our scaled random number and we re done!

double shifted = scaled + (-1.1);

So now we can put these parts together in a single function:

protected static Random random = new Random();
public static double randomInRange(double min, double max) {
  double range = max - min;
  double scaled = random.nextDouble() * range;
  double shifted = scaled + min;
  return shifted; // == (rand.nextDouble() * (max-min)) + min;
}

Of course, this function needs some error checking for unexpected values like NaN but this answer should illustrate the general idea.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/9723765/generating-a-random-double-number-of-a-certain-range-in-java

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils