chris Frisina
chris Frisina

Reputation: 19688

How does JS return a random number?

I know if you do Math.random() it will return a random number between 0 (inclusive) and 1 (exclusive), but where can I find out how JS chooses to return this number?

The MDN page does not include the lower level code.

According to wikipedia here, there are many methods to get a random number, but which method is JS using.

Upvotes: 0

Views: 301

Answers (2)

user1693593
user1693593

Reputation:

It's up to the JavaScript engine vendor to choose which random number generator they want to use.

As long as it produces a "random" number in the interval [0, 1> they will fit the ECMA specification:

15.8.2.14 random()

Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy.

Source:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.8.2.14

The vendors doesn't list what algorithm they use (as far as I could see) so unless you want to browse through the source code (where possible) you can't find out (easily anyways).

(If you are asking in relation to security: don't use the built-in one from either browsers as they are not suitable for this purpose.)

Upvotes: 3

Gravy
Gravy

Reputation: 12445

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

Upvotes: 0

Related Questions