Share JSXGraph: example "Binomial distribution"

JSXGraph
Share JSXGraph: example "Binomial distribution"
This website is a beta version. The official release will be in **2023**.

Binomial distribution

In general, if the random variable $X$ follows the binomial distribution with parameters $n \in \mathbb{N}$ and $p \in [0,1]$, we write $X \simeq B(n, p)$. The probability of getting exactly $k$ successes in n independent Bernoulli trials is given by the probability mass function: $$ Pr(X=k) = \binom{n}{k}p^k(1−p)^{n−k} $$ for $k=0,1, \ldots n$ and $0$ else. From a technical point of view, this example uses two boards which are connected by `board1.addChild(board)`.
// Define the ids of your boards in BOARDID0, BOARDID1,...

const board1 = JXG.JSXGraph.initBoard(BOARDID0, {
    boundingbox: [-0.3, 0, 1.3, -4],
    axis: false
});
var prob = board1.create('slider', [
    [0, -2],
    [1, -2],
    [0, .5, 1]
], {
    name: 'p'
});

const board = JXG.JSXGraph.initBoard(BOARDID1, {
    boundingbox: [-1, 1.1, 21, -.1],
    axis: true,
    showCopyright: false
});
board1.addChild(board);

for (let i = 0; i <= 20; i++) {
    board.create('point', [i, () => binomial(20, i, prob.Value())], {
        name: ''
    });
}

var f = board.create('functiongraph', [function(x) {
    var n, dist = 0;
    for (n = 0; n < 20 + 1; n++) {
        if (x < n) {
            return dist;
        }
        dist = dist + binomial(20, n, prob.Value());
    }
    return dist;
}]);

function binomial(n, k, p) {
    var x, p1 = 1,
        p2 = 1,
        coeff = 1;

    for (x = n - k + 1; x < n + 1; x++) {
        coeff *= x;
    }
    for (x = 1; x < k + 1; x++) {
        coeff /= x;
    }

    for (x = 0; x < k; x++) {
        p1 *= p;
    }

    for (x = 0; x < n - k; x++) {
        p2 *= (1 - p);
    }

    return coeff * p1 * p2;
}