-1

I've got a question regarding the usage of Math.ceil() together with Math.random() in Java in order to get the numbers from 1 to x.

int number;
  number =  (int) (Math.ceil(0) * 1);
  System.out.println("number generated was: " + number);

This code will return 0, as expected - 0 * 1 is 0.

    int randomNumber;
    do {
        randomNumber = (int) Math.ceil(Math.random() * 1);
        System.out.println("Random number generated was: " + randomNumber);
    }while (randomNumber != 0);

Then how come this will always return 1? I don't get it - when accessing the Math.random() it reads: "return a pseudorandom {@code double} greater than or equal to {@code 0.0} and less than {@code 1.0}"

That should still allow for the case 0 * 1. Can someone please explain this to me?

John Doe
  • 19
  • 1
  • your question has nothing to do with Math.ceil(), it's just to do with Math.random(). To avoid confusion you may simplify question like this --> why isn't Math.random() outputting 0 ever? – RajatJ Apr 17 '17 at 11:43
  • Theoretically, there are infinite real numbers between 0 and 1, so the probability of randomly getting any specific one of them is practically 0 (of course in programming languages, this is not true, but this should give you an idea of why you might be waiting for some time before that loop ends). – vefthym Apr 17 '17 at 11:46

2 Answers2

2

While it is possible that Math.random() may return zero exactly, it is not particularly likely. Hence, the loop will appear to run indefinitely although at some point it will eventually terminate.

To get an idea of how many doubles may he returned by Math.random() (i.e. how many doubles there are between 0 and 1), have a look at this SO answer, which estimates the number:

Excluding denormalized &c, I believe the count would be 1023 times 2**52.

So the chance of hitting exactly zero is roughly one out of 2^52. Don't hold your breath waiting for this to happen.

Community
  • 1
  • 1
Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
0

This is what the javadoc says:

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range. When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

So, yes, it will return 0 at some point of time and terminate the loop. However, as it being random, it will be difficult to derermine exactly when it will return 0 and hence, your loop might terminate after a couple of iteration or might take a while.

Darshan Mehta
  • 27,835
  • 7
  • 53
  • 81