Coding for Kids

Math Object: Random Numbers

Getting Random Numbers

In many programs, especially games, you want to be able to get random numbers. You don't always want your character to do 55 points of damage, right? Maybe they should sometimes get a lucky double hit or once in a while the enemy might dodge the attack. For these kinds of things, you need random numbers.

Technically speaking, a computer can't really generate a random number. It can only report back from some kind of seed that generates a number set. This just means that you might find that patterns happen even though the numbers are supposed to be random. We call these pseudorandom numbers, if we're being technical.

Use Math.random(); to generate a pseudorandom number between 0 and 1. At first glance, you may think that's crazy. What numbers between 0 and 1?! Decimals! Just so you know, these start at 0 and go up to, but not including, 1.

That's nice, but we often need a more controlled set of numbers, like whole numbers 0 to 5 or 1 to 10 or 2 to 18 (to use our previous example). These can be easily achieved. Let's tackle the first one first.

If you need a value from 0 to 5, all you need to do is multiply the Math.random() by 5. This will give you any value from 0 up to (but not including) 5.

What if you need whole numbers? Now you need to wrap that with Math.floor(). Notice, you get five possible outcomes.

Getting random numbers within a range

Coding for Kids Sidenote: Random numbers are used a lot. The information above is more than enough to get your started. This next section gets a little code-heavy and I create a helper function here. You may not be ready for that part yet. You can always come back later!

Ok, what about 2 through 18 or any other kind of range? It's easy enough. You need the range and the starting value. Is the top of your range to be included? If so, add 1 to your range.

Here's the generic code. You have to assign high and low first.

This would be a great helper function you could use in any program!

This function is great as long as you don't mess with the numbers. If you put in getRandomInteger(7, 4); you'd only get 5 and 6 as possible numbers instead! Well, the range would now be 4 - 7 + 1 which is -2. And Math.random() * -2 will give you values from 0 to -2. Once you Math.floor() it, you only get -2 or -1. Add those to the "low" 7 value and you only get 5 or 6.

We could fix it using Math.min() and Math.max() if we really wanted to. Let's see how.

May the random moments be the most exciting!

—Dr. Wolf