JavaScript: Generating Random NumbersWhile the JavaScript Math library includes a method for generating random numbers, it's not always clear how to incorporate it into your code. Math.rand() functionHere'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 integerIn 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. First attempt: var rand = Math.round(Math.random() * 6);
Interestingly, this can also be written as:
The round method rounds a floating point number to the nearest integer. Result: 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 the 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. Result: Already the results look much better:
Best practice: The only thing left to do is to shift the values to the right. var rand = 1 + Math.floor(Math.random() * 6);
Note: We could also use the Math.ceil method, but it's better coding practice to round down rather than up, and to work from zero rather than one. Result: Finally, we've achieved our goal:
Note: The JavaScript documentation describes the random method as a pseudo-random number generator as in some situations the results can be predictable. If you need truly random numbers you are better off using a server-side language such as PHP. Dice-rolling functionNow 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. // Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function rollDie(sides)
{
if(!sides) sides = 6;
with(Math) return 1 + floor(random() * sides);
}
function rollDice(number, sides)
{
var total = 0;
while(number-- > 0) total += rollDie(sides);
return total;
}
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
Working ExampleThe graph below shows the result of 1,000 rolls of three six-sided dice (3d6): [Add 100 random samples] [Zero graph] The result should be a familiar bell curve. ReferencesSend Feedback |
|||||||||||||||||||||
|
© Copyright 2010 Chirp Internet
- Page Last Modified: 22 November 2009
|
|||||||||||||||||||||