Skip to content

Instantly share code, notes, and snippets.

@SCdF
Created June 16, 2017 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SCdF/f8c954d7fc49bc4ee96a134ff2fb867c to your computer and use it in GitHub Desktop.
Save SCdF/f8c954d7fc49bc4ee96a134ff2fb867c to your computer and use it in GitHub Desktop.
Attempting to work out which algorithm to use
var randomBytes = require('crypto').randomBytes;
var RANDOM_GENERATORS = {
'randomUInt8Crypto': function() {
return randomBytes(1).readUInt8();
},
'randomUInt8Old': function() {
return 0 | Math.random() * 256;
}
};
var ALGORITHMS = {
'Current': function(randomUInt8, radix) {
return 0 | Math.random() * radix;
},
'While Loop': function(randomUInt8, radix) {
var maxRandom = 255 - (256 % radix);
var randomValue;
do {
randomValue = randomUInt8();
} while (randomValue > maxRandom);
return randomValue % radix;
},
'Round with radix to 0': function(randomUInt8, radix) {
var result = Math.round(randomUInt8() / 256 * radix);
return result === radix ? 0 : result;
},
'Floor': function(randomUInt8, radix) {
return Math.floor(randomUInt8() / 256 * radix);
}
};
var RADIX = 10;
var ROUNDS = 10000000;
var IDEAL = ROUNDS / RADIX;
var MORE_DETAIL = false;
function devation(value) {
return IDEAL - value;
}
function test(algoKey, randomUInt8Key) {
var algo = ALGORITHMS[algoKey];
var randomUInt8 = RANDOM_GENERATORS[randomUInt8Key];
var results = [];
for (var i = 0; i < RADIX; i++) { results[i] = 0; }
var before = Date.now();
for (var i = 0; i < ROUNDS; i++) { results[algo(randomUInt8, RADIX)] += 1; }
var after = Date.now();
var deviations = results.map(devation);
var averageDeviation = deviations.map(Math.abs).reduce(function(a, b) { return a + b; }) / RADIX;
console.log(algoKey, 'with', randomUInt8Key, 'took', after - before, 'millis, with', averageDeviation, '"average" deviance');
if (MORE_DETAIL) {
results.forEach(function(result, idx) {
console.log('', idx, '\t', result, '\t', devation(result));
});
}
}
Object.keys(ALGORITHMS).map(function(algoKey) {
Object.keys(RANDOM_GENERATORS).map(function(randomUInt8Key) {
test(algoKey, randomUInt8Key);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment