Search code examples
javarandomcastingintegerdouble

Is it possible to generate a random double in Java without any pre-defined boundaries?


I read about Math.random() and Random and went through almost every post regarding generating random number on stack overflow.

I still can't figure out how to generate a random number without a per-defined boundaries.

I mean, I know it's possible to write

Random random = new Random();
int mynumber = random.nextInt(max-min) + min;

but what if I don't want to supply these max and min? what if I want it to be also generated?

Bottom line, my purpose is to generate a random number, which can be also negative in the range of INT_MAX and INT_MIN.

I tried several ways:

 int max = (int)Math.random();
 int min = (int)Math.random();
 double myNumber = new Random().nextInt(max - min) + min;

does not work because (int)Math.random() always gets rounded to 0.

I also tried:

int max = Integer.MAX_VALUE;
        int min = Integer.MIN_VALUE;
        double myNumber = new Random().nextInt(max - min) + min;

and I get The call to 'nextInt' always fails as index is out of bounds .

My purpose is to generate a random double, but Random ().nextInt(x,y) gets only int as x and y. and to do that without supplying pre-defined values of max and min.

How would you suggest me to do that? To generate a random and different double at each run of the program?


Solution

  • Directly use Random#nextInt without arguments.

    Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 232 possible int values are produced with (approximately) equal probability.

    int randomInt = ThreadLocalRandom.current().nextInt();