Share JSXGraph: example "Approximate π (Pi) with Monte-Carlo method"

JSXGraph
Share JSXGraph: example "Approximate π (Pi) with Monte-Carlo method"
This website is a beta version. The official release will be in **2023**.

Approximate π (Pi) with Monte-Carlo method

At construction time each point receives a function pair as coordinates. In each update, these functions (which call `Math.random()`) are called. Thus, in each update each point receives new random coordinates. The 50 points are updated on `move` events. This can be used to calculate $\pi$ using statistics. In each update we count the number of points inside the circle (with midpoint [0,0] and radius 1) and outside the circle. The points are restricted to the square with midpoint [0,0] and edges of length 2. We add a `mouseover` event listener to the JSXGraph to trigger the repositioning of the points on every mouse move.
// Define the id of your board in BOARDID

const board = JXG.JSXGraph.initBoard(BOARDID, {
    boundingbox: [-1, 1, 1, -1],
    axis: true,
    pan: { needTwoFingers: true }
});

var c, i, count = 0,
    tin = 0,
    tout = 0,
    p = [],
    updateText;
var c = board.create('circle', [
    [0, 0], 1
]);

p = [];
for (var i = 0; i < 50; i++) {
    p[i] = board.create('point',
        [function() {
            return 2 * Math.random() - 1;
        }, function() {
            return 2 * Math.random() - 1;
        }], {
            name: ' ',
            withLabel: false
        });
}

updateText = function() {
    var i, inp, outp, x, y, text = '';
    count++;

    inp = 0;
    outp = 0;

    for (i = 0; i < p.length; i++) {
        x = p[i].X();
        y = p[i].Y();

        if (x * x + y * y <= 1) {
            inp++;
        } else {
            outp++;
        }
    }
    tin += inp;
    tout += outp;

    text += 'Current:
in: ' + inp + ', out: ' + outp + ', total: ' + (inp + outp) + '; ratio: ' + (inp / (inp + outp)) + ', ratio*4: ' + (4 * inp / (inp + outp)) + '.
Total: (' + count + ' updates in total)
I´in: ' + tin + ', out: ' + tout + ', total: ' + (tin + tout) + ';
ratio: ' + (tin / (tin + tout)) + ',
ratio*4: ' + (4 * tin / (tin + tout)); document.getElementById('resulttext').innerHTML = text; } board.on('update', updateText); JXG.addEvent(document.getElementById(BOARDID), 'mousemove', function() { this.update(); }, board);
<div id="resulttext"></div>