how to calculate the binomial distribution in javascript

To calculate the binomial distribution in JavaScript, you can use the mathjs library. First, install mathjs using npm:

index.tsx
npm install mathjs
19 chars
2 lines

Then, you can use the math.binom function to calculate the probability of getting k successes in n trials with probability of success p. Here's an example:

index.tsx
const math = require('mathjs');

// Probability of getting 2 heads in 5 coin flips (assuming a fair coin)
const n = 5;
const k = 2;
const p = 0.5;
const probability = math.binom(n, k) * p**k * (1-p)**(n-k);

console.log(probability); // prints 0.3125
251 chars
10 lines

In this example, we're calculating the probability of getting exactly 2 heads in 5 coin flips, assuming a fair coin. We use the math.binom function to calculate the binomial coefficient (n choose k). We then multiply by p**k (the probability of getting k successes) and (1-p)**(n-k) (the probability of getting n-k failures).

gistlibby LogSnag