Skip to content

Instantly share code, notes, and snippets.

@bycoffe
Created September 9, 2011 20:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bycoffe/1207194 to your computer and use it in GitHub Desktop.
Save bycoffe/1207194 to your computer and use it in GitHub Desktop.
Gaussian smoothing function in JavaScript
// Adapted from http://www.swharden.com/blog/2008-11-17-linear-data-smoothing-in-python/
var smooth = function (list, degree) {
var win = degree*2-1;
weight = _.range(0, win).map(function (x) { return 1.0; });
weightGauss = [];
for (i in _.range(0, win)) {
i = i-degree+1;
frac = i/win;
gauss = 1 / Math.exp((4*(frac))*(4*(frac)));
weightGauss.push(gauss);
}
weight = _(weightGauss).zip(weight).map(function (x) { return x[0]*x[1]; });
smoothed = _.range(0, (list.length+1)-win).map(function (x) { return 0.0; });
for (i=0; i < smoothed.length; i++) {
smoothed[i] = _(list.slice(i, i+win)).zip(weight).map(function (x) { return x[0]*x[1]; }).reduce(function (memo, num){ return memo + num; }, 0) / _(weight).reduce(function (memo, num){ return memo + num; }, 0);
}
return smoothed;
}
@tomeroto
Copy link

tomeroto commented Mar 9, 2020

hello, how to use this function? I face of error: Uncaught ReferenceError: _ is not defined

@bycoffe
Copy link
Author

bycoffe commented Mar 9, 2020

_ is underscore.js, so you'll need to install that and do something like this at the top of the script:

var _ = require('underscore');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment