Полезная информация

JavaScript: The Definitive Guide

Previous Chapter 21
JavaScript Reference

Math.random() Function


Math.random() Function---return a pseudo-random number


Navigator 3.0; buggy in Internet Explorer 3.0; Unix platforms only for Navigator 2.0






A pseudo-random number between 0.0 and 1.0.


Math.random() returns a psuedo-random number between 0.0 and 1.0. Note that in Navigator 2.0, this function only works for Unix platforms. In Internet Explorer 3.0, Math.random() generates pseudo-random numbers, but is not randomly seeded, so it generates the same sequence of numbers each time the browser is started.


Since Math.random() does not work on all platforms, you should not rely on it if you want your scripts to be really portable. If you need only a single pseudo-random number, you can often use a portion of the current time, such as (new Date()).getSeconds()).

If you need need a sequence of more reliably pseudo-random numbers (for a game, perhaps), you'll have to write your own pseudo-random number generator. The following code is based on a linear congruential algorithm in the book Numerical Recipes, and produces simple, non-cryptographic, pseudo-random numbers:

function random() { 
  random.seed = (random.seed*random.a + random.c) % random.m; 
  return random.seed / random.m; 
random.m=714025; random.a=4096; random.c=150889; 
random.seed = (new Date()).getTime()%random.m;


Internet Explorer 3.0 does not randomly seed its random-number generator, so it generates the same sequence of random numbers each time the browser starts up. This bug will be fixed in a future release.

See Also


Previous Home Next
Math.pow() Book Index Math.round()

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell