Created
November 10, 2017 16:17
-
-
Save phihag/dc209bf12a5faa0f26be92874d1b5d3f to your computer and use it in GitHub Desktop.
Check for random sampling
This file contains hidden or 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
const assert = require('assert'); | |
const checks = { | |
/* original_post: (val, range, maxNum) => { | |
return val + range - (val % range) < maxNum; | |
},*/ | |
traditional: (val, range, maxNum) => { | |
return val < Math.floor(maxNum / range) * range; | |
}, | |
correct: (val, range, maxNum) => { | |
return val < maxNum - maxNum % range; | |
}, | |
}; | |
const maxNum = 256; | |
for (let range = 1;range < maxNum;range++) { | |
const all_counts = {}; | |
for (const check_name in checks) { | |
const check = checks[check_name]; | |
const counts = new Array(range).fill(0); | |
for (let val = 0;val < maxNum;val++) { | |
if (check(val, range, maxNum)) { | |
const res = val % range; | |
counts[res]++; | |
} | |
} | |
all_counts[check_name] = counts; | |
for (c of counts) { | |
if (c !== counts[0]) { | |
throw new Error( | |
'[' + check_name + '] Biased for range ' + range + | |
': ' + JSON.stringify(counts)); | |
} | |
} | |
} | |
const ref_counts = all_counts.traditional; | |
for (const check_name in all_counts) { | |
const this_counts = all_counts[check_name]; | |
assert.deepStrictEqual( | |
this_counts, ref_counts, | |
'Counts of ' + check_name + ' incorrect for range = ' + range + ': ' + JSON.stringify(this_counts)); | |
} | |
} | |
console.log('All tests passed'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment