5 ms·
Wow. I took this to the nth degree to convince a colleague. Very little variance between biased and unbiased figures: [javascript] var sim = () =>{
by twodave 9y ago
Wow. I took this to the nth degree to convince a colleague. Very little variance between biased and unbiased figures:
[javascript]
var sim = () =>{
var percentChanceOfHeads = 99;
var getRandomArbitrary = (min, max) => {
return Math.random() * (max - min) + min;
};
let heads = 0, tails = 0;
for (let i = 0; i < 100000; i++){
var test1 = getRandomArbitrary(0,100);
var test2 = getRandomArbitrary(0,100);
if (test1 > percentChanceOfHeads && test2 > percentChanceOfHeads) continue;
if (test1 <= percentChanceOfHeads && test2 <= percentChanceOfHeads) continue;
if (test1 <= percentChanceOfHeads) heads++;
else tails++;
}
let total = heads + tails;
let heads2 = 0, tails2 = 0;
for (let i = 0; i < total; i++){
var test1 = getRandomArbitrary(0,100);
if (test1 <= 50) heads2++;
else tails2++;
}
var distanceClosed = Math.abs(heads-tails) - Math.abs(heads2-tails2);
return distanceClosed;
};
for(let i=0;i<10000;i++)temp.push(sim()); console.log('avg variance:' + temp.reduce((a,c)=>a+c)/10000);
- TekMol 9y agoShorter version: chanceOfHead=0.9; heads=0; tails=0; flips=0; while(flips<1000) { coin1=Math.random()<chanceOfHead; coin2=Math.random()<chanceOfHead; if(coin1==coin2) continue; heads+=coin1; tails+=coin2; flips++; }; console.log(heads,tails);
- oh_sigh 9y agoOh JavaScript. Will a Boolean always on all browsers coerce itself into a 0 or 1 if treated like a number?
- tjgq 9y agoThe Javascript coercion rules, arcane as they are, are actually part of the spec and (barring any bugs) should work across browsers.
- twodave 9y agoSure, that will get the basics. We wanted to compare it to what an unbiased set of flips of the same number would look like over time, so there's a little more to it. It's also interesting (and I guess should be obvious) to note that the "thrown out" tosses seem to be a pretty consistent ratio based on the "biased-ness" of the coin.