Skip to content

Instantly share code, notes, and snippets.

@nitobuendia
Last active July 9, 2022 07:59
Show Gist options
  • Save nitobuendia/c038107fcd1c7ccb0e4d2626e0b16330 to your computer and use it in GitHub Desktop.
Save nitobuendia/c038107fcd1c7ccb0e4d2626e0b16330 to your computer and use it in GitHub Desktop.
Basic statistics on a random number generator
const MIN_INT = 1;
const MAX_INT = 5;
const ROUNDS = 1000;
const FLOATING_ACCURACY = 2;
function getRandomInt(min = MIN_INT, max = MAX_INT){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function roundToDecimalPoints(number, decimalPoints = FLOATING_ACCURACY) {
const accuracyInTens = Math.pow(10, decimalPoints);
return Math.round(accuracyInTens * number) / accuracyInTens;
}
const results = {};
for (let i = 0; i < ROUNDS; i++) {
const randomNumber = getRandomInt();
if (!results[randomNumber]) results[randomNumber] = {value: 0};
results[randomNumber].value++;
}
const expected = roundToDecimalPoints(ROUNDS / (MAX_INT - MIN_INT + 1));
const pct_expected = roundToDecimalPoints(100 * expected / ROUNDS);
for (const key of Object.keys(results)) {
const pct = roundToDecimalPoints(100 * results[key].value / ROUNDS);
results[key].expected = expected;
results[key].diff = results[key].value - expected;
results[key].pct = pct;
results[key].pct_expected = pct_expected;
results[key].pct_diff = roundToDecimalPoints(pct - pct_expected);
}
console.table(results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment