Math.random()

This article is in need of a technical review.

Summary

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

The random number generator is seeded from the current time, as in Java.

Syntax

Math.random()

Parameters

None.

Examples

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 getRandomArbitrary(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;
}

Specifications

Specification Status Comment
ECMAScript 1st Edition. JavaScript 1.0 (UNIX Only) / JavaScript 1.1 (All platform) Standard Initial definition.
ECMAScript Language Specification 5.1th Edition (ECMA-262) Standard  
ECMAScript Language Specification 6th Edition (ECMA-262) Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

 

Document Tags and Contributors

Last updated by: nosebleed,