Skip to content

Instantly share code, notes, and snippets.

@dirkmc
Last active April 18, 2024 11:26
Show Gist options
  • Save dirkmc/3dc762bcab3b792d4337d64f3ad4d638 to your computer and use it in GitHub Desktop.
Save dirkmc/3dc762bcab3b792d4337d64f3ad4d638 to your computer and use it in GitHub Desktop.
const Decimal = require('decimal.js');
function cdf(n, k, p) {
const probability = new Decimal(p);
const lambda = new Decimal(n).times(probability);
let total = new Decimal(0);
for (let i = 0; i <= n-k; i++) {
const res = lambda.pow(i).dividedBy(factorial(i));
total = total.plus(res);
}
return total.times(new Decimal(Math.E).pow(lambda.negated()));
}
function factorial (n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
// Usage: node probs.js <failure pct> <k> <n>
// node probs.js 10 24 36
const [failurePct, k, n] = process.argv.slice(2);
const failureProbability = new Decimal(failurePct).dividedBy(100);
const kThreshold = new Decimal(k);
const nShards = new Decimal(n);
const cdfValue = cdf(nShards, kThreshold, failureProbability);
const nineCount = ((cdfValue.toString().match(/^0\.(9*)/) || [])[1] || []).length;
const cdfStr = cdfValue.times(100).toString()
console.log(`${failurePct}% / month, k ${kThreshold} / n ${nShards}: ${cdfStr}% (${nineCount} nines)`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment