Skip to content

Instantly share code, notes, and snippets.

@phihag
Created November 10, 2017 16:17
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 phihag/dc209bf12a5faa0f26be92874d1b5d3f to your computer and use it in GitHub Desktop.
Save phihag/dc209bf12a5faa0f26be92874d1b5d3f to your computer and use it in GitHub Desktop.
Check for random sampling
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