Created
November 28, 2018 08:20
-
-
Save fractalbach/b350a6eb7a348c7a5884afef3ae71bff to your computer and use it in GitHub Desktop.
javascript random number experiment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Here's an example run calling the function
Which means:
Graph