# bayes.js: A Small Library for Doing MCMC in the Browser

(This article was first published on Publishable Stuff, and kindly contributed to R-bloggers)

Bayesian data analysis is cool, Markov chain Monte Carlo is the cool technique that makes Bayesian data analysis possible, and wouldn’t it be coolness if you could do all of this in the browser? That was what I thought, at least, and I’ve now made bayes.js: A small JavaScript library that implements an adaptive MCMC sampler and a couple of probability distributions, and that makes it relatively easy to implement simple Bayesian models in JavaScript.

Here is a motivating example: Say that you have the heights of the last ten American presidents…

// The heights of the last ten American presidents in cm, from Kennedy to Obama
var heights = [183, 192, 182, 183, 177, 185, 188, 188, 182, 185];


… and that you would like to fit a Bayesian model assuming a Normal distribution to this data. Well, you can do that right now by clicking “Start sampling” below! This will run an MCMC sampler in your browser implemented in JavaScript.

{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
}
var clear_samples;
var sample_loop;
var stop_sample_loop;
var heights = [183, 192, 182, 183, 177, 185, 188, 188, 182, 185];
var params = {
mu: {type: "real"},
sigma: {type: "real", lower: 0}};
var log_post = function(state, heights) {
var log_post = 0;
// Priors (here sloppy and vague...)
log_post += ld.norm(state.mu, 0, 1000);
log_post += ld.unif(state.sigma, 0, 1000);
// Likelihood
for(var i = 0; i ' +
'

' +
'

' +
'
Source:: R News