1

Possible Duplicate:
How random is JavaScript’s Math.random?

Exactly what algorithm does Math.random() use to generate its random numbers?

Given the format of a double, and the range that Math.random() generates, how many possible outcomes are there?

Taking into account the above and the (in)accuracies of floating-point numbers, what are the odds of Math.random() returning exactly 0?

Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Good question! I'd just recommend not counting on it. Set your own probability by multiplying the result and rounding that as usual, unless you need a one-in-billions chance. – Ry- Jan 08 '13 at 02:24
  • Have you checked out https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random ? – MadSkunk Jan 08 '13 at 02:24
  • 1
    See other questions like [this one](http://stackoverflow.com/questions/578700/how-trustworthy-is-javascripts-random-implementation-in-various-browsers) and [this one](http://stackoverflow.com/questions/1062902/how-random-is-javascripts-math-random) – Pointy Jan 08 '13 at 02:25
  • 1
    I found this on V8, it might be helpful http://code.google.com/searchframe#W9JxUuHYyMg/trunk/src/hydrogen.cc&q=MathRandom%20package:v8%5C.googlecode%5C.com&l=9158 – elclanrs Jan 08 '13 at 02:25
  • From the [spec](http://es5.github.com/#x15.8.2.14): *"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."*. – Felix Kling Jan 08 '13 at 02:34

2 Answers2

1

It uses a pseudo random number generator with the seed being the time at which it is invoked.

This page has some images to compare truly random noise to pseudo random noise. Interesting pattern: http://boallen.com/random-numbers.html

The JS pseudo random may not necessarily be exactly like that, but should be close.

Tor Valamo
  • 33,261
  • 11
  • 73
  • 81
0

Math.random uses a uniform distribution of numbers.

  • Yes, but... what numbers? (See last paragraph) – Ry- Jan 08 '13 at 02:32
  • 2
    The inaccuracy of floating point number is pretty tricky. In my mind, if you simply extend the range so that every selected number is whole (integer) and then divide it by a constant to make them fit to your desired range, every number in it would stand an equal chance of appearing. Over all a uniform distribution simply means a horizontal line in the probability distribution curve. That means that everything has an equal chance at least theoretically. – AmbuSreedharan Jan 08 '13 at 02:38
  • It is not uniform. It is pseudo random, see my answer. – Tor Valamo Jan 16 '13 at 04:48