Skip to content

Instantly share code, notes, and snippets.

@fractalbach
Created November 28, 2018 08:20
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 fractalbach/b350a6eb7a348c7a5884afef3ae71bff to your computer and use it in GitHub Desktop.
Save fractalbach/b350a6eb7a348c7a5884afef3ae71bff to your computer and use it in GitHub Desktop.
javascript random number experiment
/*
randintNorm returns an integer in [min, max] including min and max.
The distribution will be closer to a normal distribution because it adds
2 instances of Math.random() together, like rolling 2 dice and adding them together.
*/
const randintNorm = (min, max)=> {
min = Math.ceil(min);
max = Math.floor(max);
let r = (Math.random() + Math.random()) / 2;
return Math.floor(r * (max - min + 1)) + min;
};
/*
testRandDist creates a Mapping of (result value from randint) --> (number of hits)
Using "dice rolls" as a metaphor, nTests is the number of times you roll the dice,
the result is the sum of the dice you roll, and the map is where you tally up
the number of times that sum appears.
*/
const testRandDist = (min, max, fn, nTests)=> {
let dist = new Map();
for (let i=0; i<nTests; i++) {
let val = fn(min, max);
if (dist.has(val) !== true) {
dist.set(val, 1);
} else {
let n = dist.get(val);
dist.set(val, n+1);
}
}
return dist;
};
/*
exampleTest calls the test, and uses the Map object to create a
really simple terminal graph of the distribution.
*/
const exampleTest = (min, max, nTests)=> {
let map = testRandDist(min, max, randintNorm, nTests);
let arr = [];
for (let i=0; i<(max-min+1); i++) {
let x = min + i;
if (map.has(x)) {
let v = map.get(x);
console.log(x, v, '='.repeat(v));
} else {
console.log(x, 0);
}
}
};
@fractalbach
Copy link
Author

Example

Here's an example run calling the function

exampleTest(1, 40, 4000)

Which means:

  • min integer = 1
  • max integer = 40
  • number of generated numbers = 4000

Graph

exampledist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment