Goussian Kernel

by mslocum

JavaScript

function gaussianKernel(deviation, maxSize) {
    var ret = [],
        d1 = [],
        temp = [],
        maxSize = Infinity,
        i = 0, j;

    while ((!d1.length || d1[0]) && i - 1 < (maxSize + 1) / 2) {
        d1.unshift(
            roundTo(1 / (Math.sqrt(2 * Math.PI) * deviation) * Math.exp(-(i) * (i) / (2 * deviation * deviation)), 6)
        );
        i++;
    }
    d1.shift(); // we don't need the 0
    
    d1 = d1.concat( d1.slice(0, -1).reverse() );
    
    for (i = 0; i < d1.length; i++) {
        temp = [];
        for (j = 0; j < d1.length; j++) {
            temp.push(d1[i] * d1[j]);
        }
        ret.push(temp);
    }
   
    return ret;
}

function roundTo(num, decimals) {
	var shift = Math.pow(10, decimals);
	return Math.round(num * shift) / shift;
}


var sum = 0,
    kernel = gaussianKernel(1);
kernel.forEach(function(row) { 
    row.forEach(function(i) {
        sum += i; 
    });
});
console.log(kernel, sum);

//sum = 0;
//kernel = d1Kernel(2.5);
//kernel.forEach(function(i) { sum += i; });
//console.log(kernel, sum);

//0.000003	0.000229	0.005977	0.060598	0.24173	0.382925	0.24173	0.060598	0.005977	0.000229	0.000003