Random Numbers ♦ Part 3

More Information

Luckily for us, JavaScript has a built-in object called Math. The Math object has many properties and methods for mathematical computations, and a complete reference for all of these can be found here.

However, for the purposes of creating random number generators, we only need to be concerned with two of them: its Math.random() method, and its Math.floor() method.

By itself, Math.random() generates a random floating-point number between 0 and 1. The number it generates will never be 1, and it will probably never be exactly 0 either. Instead, it will be a number like 0.7458165847047881. And that might not seem very useful at first. But that is the sole reason for this tutorial.

One way to get a more useful range of random numbers is multiply Math.random() by some upper-limit number like 10. So, if you use some code like Math.random() * 10, you will generate a random number between 0 and 10. However the number it generates will never be 10, and it will probably never be exactly 0 either. Instead, it will a number like 7.458165847047881 which still seems rather useless when what you really wanted was an integer.

The way we change Math.random() * 10 into an integer value is by using the Math.floor() method which rounds that floating- point number down to the nearest integer. For instance, if we use Math.random() * 10 and it generates the number 6.936671607915301, that same number will round down to the integer 6 using Math.floor(), even though the number 6.936671607915301 is actually closer to 7. But that is just fine with us because Math.floor() does what we want it to do much better than Math.ceil() which rounds floating-point numbers up rather than down.

Math.floor(Math.random() * 10) is the new random number generator we have now. And it generates random integers between between 0 and 10 (actually 0 to 9). However the number it generates will never be 10, even though it will sometimes be 0 since Math.floor() causes some floating-point numbers to round all the way down to 0. Now we are getting closer to a useful random number generator.

But what if we wanted to generate random numbers between 0 and 10?

That's actually an easy problem to solve. To do that, we simply use...
Math.floor(Math.random() * 11) which generates a random number between 0 and 11. However the number it generates will never be 11, but it will sometimes be 10 and it will sometimes be 0. Problem solved!

But what if we wanted to generate random numbers between 1 and 10?

Sometimes we find that zeroes are not really useful at all. That's actually another easy problem to solve. To do that, we simply add 1 and use...
Math.floor(Math.random() * 10) + 1 which generates a random number between 0 and 9 and then adds 1 to it! Once again, this problem is easily solved!