home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


JavaScript: The Definitive Guide

Previous Chapter 21
JavaScript Reference
Next
 

Math.random() Function

Name

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

Availability

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

Synopsis

Math.random()

Arguments

None.

Returns

A pseudo-random number between 0.0 and 1.0.

Description

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.

Usage

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;

Bugs

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.


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