Random Numbers
The random() method returns a pseudo-randomly selected number between 0.0 and 1.0. The range includes 0.0 but not 1.0. In other words: 0.0 <= Math.random() < 1.0. To get a number in a different range, you can perform arithmetic on the value returned by the random method. For example, to generate an integer between 0 and 9, you would write:
int number = (int)(Math.random() * 10);
By multiplying the value by 10, the range of possible values becomes 0.0 <= number < 10.0.
Using Math.random works well when you need to generate a single random number. If you need to generate a series of random numbers, you should create an instance of java.util.Random and invoke methods on that object to generate numbers.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Cameron Finch wrote:I used 1 + (int)(Math.random() * 1000).
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
There are worse crimes than burning books. One of them is not reading them. Ray Bradbury
that is what lots of people think, but it isn't correct. It says clearly, earlier in this thread, how to get a number between 1..1000 inclusive. I still would prefer(int)(Math.random() * 1000) will give you a pseudo‑random int between 0..999. Putting the () in the wrong places around the cast will probably give you a pseudo‑random int between 0..0Christopher McKay wrote:Usually multiplying it by 1000 gives you a number between 1 and 1000. . . .
Campbell Ritchie wrote:
that is what lots of people think, but it isn't correct. It says clearly, earlier in this thread, how to get a number between 1..1000 inclusive. I still would prefer(int)(Math.random() * 1000) will give you a pseudo‑random int between 0..999. Putting the () in the wrong places around the cast will proabbly give you a pseudo‑random int between 0..0 :wink:Christopher McKay wrote:Usually multiplying it by 1000 gives you a number between 1 and 1000. . . .
It's a pleasure to see superheros taking such an interest in science. And this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|