Random Number GeneratorsReference > Science > Technology > Beginner Programming Tips
The first programs I ever wrote were games. They were silly games, and nobody but me wanted to play them, but they were definitely good programming experience. Of course, if you are writing a game program, you need to generate random numbers, otherwise the game gets quite tedious, doing the same thing over and over and over...
So I very quickly discovered this little snippet of code, and used it extensively without ever bothering to look at what was actually happening "behind the scenes."
'Pick A Random Number Between 1 and 10 Inclusive
âMyRandomNumber = Int(Rnd * 10) + 1
Here is what's happening. "Rnd" is the actual Random Number Generator. What does it generate? It generates a Random number between 0 and 1, possibly including 0, but never including 1. So when you multiply it by ten, you get a number which is somewhere between zero and ten. Possibly including 0, but never including ten.
And here comes the handy math function "Int," which takes the integer part of a decimal value. For example, the integer part of 2.3 is 2. The integer part of 6.9 is 6.
So when you take the integer part of your random number times ten, you get any integer from zero to nine, but not ten. Thus, to get a random number between one and ten, you just need to add one to your random number.
Now take a look at this piece of code:
'Pick A Random Number Between 5 and 9 Inclusive
âMyRandomNumber = Int(Rnd * 5) + 5
Do you see what's happening here? If you are looking for a random number between five and ten, you have five possible values (5, 6, 7, 8, and 9). So you have to multiply the random generator by five. Of course, that just gives you the following values: 0, 1, 2, 3, or 4. So you need to add five to get the values you want.
Want to try another one? Let's say you want the computer to pick a random multiple of 5 between 0 and 50 inclusive. Here's the code for it; see if you can figure out why it works. And when you've done that, try some of the Other Scenarios listed below.
'Pick A Random Multiple of 5, between 0 and 50
âMyRandomNumber = 5* Int(Rnd * 11)