Binomial Simulator

by wio_dude

HTML

<canvas id="canvas" height="300"></canvas>
<br />
<label for="probability">Probability:</label>
<input id="probability" type="text" value="0.5" />
<br />
<label for="trials">Trials:</label>
<input id="trials" type="text" value="50" />
<br />
<input id="run" type="button" value="Run" />

CSS

canvas {
    border: 1px solid black;
}

JavaScript

var byId = document.getElementById.bind(document);
var canvas = byId("canvas");
var context = canvas.getContext("2d");
var bounds = {
    x: 0,
    y: 0,
    width: canvas.width,
    height: canvas.height    
};
var pdfbounds = {
    x: bounds.x + 10,
    y: bounds.y + 10,
    width: bounds.width - 20,
    height: (bounds.height - 30)/2
};
var cdfbounds = {
    x: bounds.x + 10,
    y: pdfbounds.y + pdfbounds.height + 10,
    width: bounds.width - 20,
    height: (bounds.height - 30)/2
};

var loop = null;

function clear(context) {
    // Store the current transformation matrix
    context.save();
    
    // Use the identity matrix while clearing the canvas
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0, canvas.width, canvas.height);
    
    // Restore the transform
    context.restore();
}

function drawrect(context, x, y, w, h, style, fill) {
    if (typeof style === "undefined") {
        style = "#000000";
    }
    if (typeof fill === "undefined") {
        fill = false;
    }
    var oldStyle;
    if (fill) {
        oldStyle = context.fillStyle;
        context.fillStyle = style;
    } else {
        oldStyle = context.strokeStyle;
        context.strokeStyle = style;
    }
    context.beginPath();
    context.rect(x, y, w, h);
    context.fill();
    if (fill) {
        context.fillStyle = oldStyle;
    } else {
        context.strokeStyle = oldStyle;
    }
}

function BinomialSimulator(p, trials) {
    this.p = p;
    this.trials = trials;
    this.history = [];
    this.simulations = 0;
    var i;
    for (i = 0; i < trials; i++) {
        this.history[i] = 0;
    }
}
BinomialSimulator.prototype.simulate = function(){
    var i, passed = 0;
    for (i = 0; i < this.trials; i++) {   
        if (Math.random() < this.p) {
            passed++;
        }
    }
    return passed;
};
BinomialSimulator.prototype.run = function(n){
    if (typeof n === "undefined") {
        n = 1;
    }
    var i;
    for (i = 0; i < n; i++) {
     ...