Search code examples
javascriptnoise-generator

laplace noise distribution in JavaScript


I want to create a web-based demonstration of differential privacy. To do this, I need a JavaScript implementation of the Laplace noise distribution.

I've been unable to find basic noise distributions in JavaScript, such as Gaussian. This is surprising, because I would like that there would be lots of cool JavaScript demos showing how the distribution builds up, draw by draw, to produce a pretty bell-shaped curve.

How do I generate a Laplace noise distribution in Javascript?


Solution

  •        function sgn(x) {
                return x < 0 ? -1 : 1;
            }
    
            // From wikipedia:
            // Lap(X) = mu - b sgn(U) ln (1-2|U|) where U is a random variable between -0.5 and 0.5
            function laplace(mu, b) {
                var U = Math.random() - 0.5;
                return mu - (b * sgn(U) * Math.log(1 - 2* Math.abs(U)));
            }
    
            function privatize(F,deltaF,epsilon) {
                return F + laplace(0.0, deltaF/epsilon);
            }