Generate a range of random even numbers in Java

The posts I read almost explained this problem, but they all use integer values. To be honest, I don't fully understand, so this problem:

I'm trying to generate random numbers ranging from (- 1554900.101) to (52952058699.3098) in Java. I wonder if anyone can explain this to me because I really want to know it

My idea: will this be the right way? 1) Generate a random integer within the specified range 2) divide the generated number by pi to obtain the floating point number / double random result

Thank you in advance

Solution

This is the idea If you want a random number in a range, let's assume that [- 1.1,2.2] starts with a simple example The length of this range is 3.3 because 2.2 – (- 1.1) = 3.3 Now most "random" functions return a number in the range [0,1] with a length of 1, so we must expand our random number to the range we need

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

Now our random number has the size we want, but we must move it on the number line to the exact value we want For this step, we only need to add the lower limit of the whole range to our scaled random number!

double shifted = scaled + (-1.1);

So now we can put these parts together:

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 requires some error checking, unexpected values such as Nan, but this answer should explain the general idea

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>