Math.random and web programming in JavaScript

According to this thread , Math.random () in JavaScript is browser or operating system dependent. Basically, this means that JavaScript does not have a standard algorithm for generating uniform random variables. This thread seems to suggest that the random number algorithm in the Chrome format is especially bad.

In my program, I try to understand how the user behaves based on some information plus random noise. I use Box-Muller's conversion to the numbers generated by Math.random () to generate Gaussian random numbers. Does this mean that users using one browser will experience different types of noise than others? Note. I use Box Muller because I don't care about speed, but I know that it can be especially sensitive to how pseudo random numbers are generated. There seems to be a lot of threads about why Math.random () is bad, but not so much in the stream, but actually used. What is the best practice? Is there something I particularly need because I use Box-Muller to convert to Gaussian numbers?

+8
javascript random
source share
2 answers

There is an xor-shift based RNG here at http://en.wikipedia.org/wiki/Xorshift with good randomness properties that should be fairly easy to port to JavaScript:

EDIT :

(function () { var x = 123456789; var y = 362436069; var z = 521288629; var w = 88675123; var f = Math.pow(2, -32); Object.defineProperty(Math, 'xor128', { value: function () { var t = x ^ (x << 11); x = y; y = z; z = w; w = w ^ (w >>> 19) ^ (t ^ (t >>> 8)); return (w >>> 0) * f; // convert to floating point } }); })(); 

Note: only 32 bits out of 128 are used to use the floating point result. Theoretically, you can combine another 20 bits from one of the other state variables to get 52 bits of the result.

The most significant problem with this I see is that it does not support sowing - it will always generate the same sequence.

+2
source share

A Box-Muller conversion only works with evenly distributed . According to MDN (last example), Math.random() will not generate evenly distributed numbers.

The ECMAScript specification says the following about Math.random() :

Returns the value of a number with a positive sign greater than or equal to 0, but less than 1, chosen randomly or in a pseudo-random way with approximately uniform distribution over this range using an implementation-dependent algorithm or strategy. This function takes no arguments.

So, this is up to the browser. The browser may not need to implement a completely evenly distributed random number generator.

Therefore, you cannot reliably implement Box-Muller's cross-browser conversion to Javascript on the browser side using Math.random()

+1
source share

All Articles