Core JavaScript 1.5 Reference:Global Objects:Math:random
From MDC
Contents |
[edit] Summary
Returns a pseudo-random number in the range [0,1) — that is, between 0 (inclusive) and 1 (exclusive). The random number generator is seeded from the current time, as in Java.
| Method of Math | |
|
Static |
|
| Implemented in: | JavaScript 1.0, NES 2.0: Unix only
JavaScript 1.1, NES 2.0: all platforms |
| ECMA Version: | ECMA-262 |
[edit] Syntax
var randomNumber = Math.random();
[edit] Parameters
None.
[edit] Notes
Note that Math is not a constructor, so you always invoke random as Math.random() and never create instances of Math. Some may thus call the method "static" due to analogy with class-based OO languages like Java.
[edit] Examples
[edit] Example: Using Math.random
Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, these ranges, excluding the one for Math.random() itself, aren't exact, and depending on the bounds it's possible in extremely rare cases (on the order of 1 in 262) to calculate the usually-excluded upper bound.
// Returns a random number between 0 (inclusive) and 1 (exclusive)
function getRandom()
{
return Math.random();
}
// Returns a random number between min and max
function getRandomArbitary(min, max)
{
return Math.random() * (max - min) + min;
}
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}