Here's a sample of random numbers generated by your browser. You should see a range of floating point numbers with up to 16 decimal places (less in some browsers):
The numbers generated are in a range from 0 to <1 or, in mathematical notation, [0,1).
Generating a random integer
In this example, we're going to simulate the rolling of a standard six-sided die. In other words, generate an integer between 1 and 6 inclusive.
var rand = Math.round(Math.random() * 6);
Interestingly, this can also be written as:
var rand = round(random() * 6);
The round method rounds a floating point number to the nearest integer.
We've generated and plotted 500 random 'rolls' of the die using the above code:
As you can see, we don't end up with an even six-way spread as you might expect. Instead you see that '0' and '6' receive around half as many results as 1 through 5, so using round isn't the way to go.
A better method:
var rand = Math.floor(Math.random() * 6);
The floor method rounds numbers down to the nearest integer.
Already the results look much better:
The only thing left to do is to shift the values to the right.
var rand = 1 + Math.floor(Math.random() * 6);
Finally, we've achieved our goal:
Now that we're clear on how to generate random integers, how about simulating rolls of multiple dice. This is probably an outdated concept now, but at one time there were thousands of people using dice with different numbers of sides for role-playing and other games.
The functions above can be called as follows:
var rand = rollDie(); # d6 var rand = rollDie(6); # d6 var rand = rollDie(20); # d20 var rand = rollDice(3); # 3d6 var rand = rollDice(3, 6); # 3d6 var rand = rollDice(2, 12); # 2d12
The graph below shows the result of 1,000 rolls of three six-sided dice (3d6):
The result should be a familiar bell curve.
Send a message to The Art of Web:
press <Esc> or click outside this box to close