secret
anonymous / fourier.js
Last active

  • Download Gist
fourier.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
Fourier.Transform = function(data) {
var N = data.length;
var frequencies = [];
 
// for every frequency...
for (var freq = 0; freq < N; freq++) {
var re = 0;
var im = 0;
 
// for every point in time...
for (var t = 0; t < N; t++) {
 
// Spin the signal _backwards_ at each frequency (as radians/s, not Hertz)
var rate = -1 * (2 * Math.PI) * freq;
 
// How far around the circle have we gone at time=t?
var time = t / N;
var distance = rate * time;
 
// datapoint * e^(-i*2*pi*f) is complex, store each part
var re_part = data[t] * Math.cos(distance);
var im_part = data[t] * Math.sin(distance);
 
// add this data point's contribution
re += re_part;
im += im_part;
}
 
// Close to zero? You're zero.
if (Math.abs(re) < 1e-10) { re = 0; }
if (Math.abs(im) < 1e-10) { im = 0; }
 
// Average contribution at this frequency
re = re / N;
im = im / N;
 
frequencies[freq] = {
re: re,
im: im,
freq: freq,
amp: Math.sqrt(re*re + im*im),
phase: Math.atan2(im, re) * 180 / Math.PI // in degrees
};
}
 
return frequencies;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.