Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers with Math.random() in Java

Tags:

java

random

For generating random numbers, I've used the formula:

(int)(Math.random() * max) + min

The formula I find on Google always seem to be:

(int)(Math.random() * (max - min) + min)

Which one's right? As far as I know, I've never gotten a number that was out of my range with my formula

like image 982
Alex Avatar asked Oct 27 '11 22:10

Alex


People also ask

What is Math random () in Java?

random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. . When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java. util.


1 Answers

Your formula generates numbers between min and min + max.

The one Google found generates numbers between min and max.

Google wins!

like image 73
pjz Avatar answered Oct 20 '22 01:10

pjz