binomial distribution in javascript

To calculate binomial distribution in javascript, we can use the following function:

index.tsx
function binomial(n, k, p) {
  const coef = factorial(n) / (factorial(k) * factorial(n - k));
  return coef * Math.pow(p, k) * Math.pow((1 - p), (n - k));
}

function factorial(num) {
  if (num === 0 || num === 1) {
    return 1;
  } else {
    return num * factorial(num - 1);
  }
}

285 chars
14 lines

The binomial(n, k, p) function takes three parameters:

  • n: the number of trials
  • k: the number of successful trials
  • p: the probability of success in each trial

The function calculates the binomial coefficient (n choose k) and multiplies it by the probability of k successes and (n-k) failures.

Here's an example of how to use this function to calculate the probability of getting exactly 3 heads in 5 coin tosses with a fair coin:

index.tsx
const n = 5; // number of trials
const k = 3; // number of successful trials
const p = 0.5; // probability of success

const prob = binomial(n, k, p);
console.log(prob); // 0.3125
180 chars
7 lines

The output shows that the probability of getting exactly 3 heads in 5 coin tosses is 0.3125 or 31.25%.

gistlibby LogSnag