# Native and non-native Random Numbers

## JavaScript performance comparison

Revision 3 of this test case created by Adam Hyland and last updated

## Preparation code

``````<script src="http://davidbau.com/encode/seedrandom-min.js"></script>
<script>

var xor = (function() {
var denom = Math.pow(2, 31),
tuple = { a : 11, b : 19, c : 8},
seed = 2463534242;
return {
getSeed : function() {
return seed;
},
setSeed : function(val) {
seed = val || Math.random() * denom;
return seed;
},
rand : function() {
//tuples
var a = tuple.a,
b = tuple.b,
c = tuple.c;

var x = seed,
t, y;

t = x^(x << a);
seed = y = (x^(x >> c))^(t^(t >> b));

return y / denom;
}
};
}());

var lcg = (function() {
// Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
var m = 4294967296,
a = 1664525,
c = 1013904223,
seed, z;
return {
setSeed : function(val) {
z = seed = val || Math.random() * m;
},
getSeed : function() {
return seed;
},
rand : function() {
z = (a * z + c) % m;
return z / m;
}
};
}());

</script>

<script>
Benchmark.prototype.setup = function() {
Math.oldrand = Math.random;
Math.seedrandom();
lcg.setSeed();
};

Benchmark.prototype.teardown = function() {
Math.random = Math.oldrand;
};

</script>
``````

## Preparation code output

<script> var xor = (function() { var denom = Math.pow(2, 31), tuple = { a : 11, b : 19, c : 8}, seed = 2463534242; return { getSeed : function() { return seed; }, setSeed : function(val) { seed = val || Math.random() * denom; return seed; }, rand : function() { //tuples var a = tuple.a, b = tuple.b, c = tuple.c; var x = seed, t, y; t = x^(x << a); seed = y = (x^(x >> c))^(t^(t >> b)); return y / denom; } }; }()); var lcg = (function() { // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes var m = 4294967296, a = 1664525, c = 1013904223, seed, z; return { setSeed : function(val) { z = seed = val || Math.random() * m; }, getSeed : function() { return seed; }, rand : function() { z = (a * z + c) % m; return z / m; } }; }()); </script>

## Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Native Math.random
``Math.oldrand();``
pending…
Bau's ARC4
``Math.random();``
pending…
XORshift
``xor.rand();``
pending…
LCG
``lcg.rand();``
pending…

## Revisions

You can edit these tests or add even more tests to this page by appending `/edit` to the URL.