Skip to content

Instantly share code, notes, and snippets.

@shovon
Created December 4, 2014 01:11
Show Gist options
  • Save shovon/c3ca8e59a5cf277c947a to your computer and use it in GitHub Desktop.
Save shovon/c3ca8e59a5cf277c947a to your computer and use it in GitHub Desktop.
Discrete Fourier Transform in JavaScript
function createComplex(real, imag) {
return {
real: real,
imag: imag
};
}
function dft(samples, inverse) {
var len = samples.length;
var arr = Array(len);
var pi2 = inverse ? Math.PI * 2 : Math.PI * (-2);
var invlen = 1 / len;
for (var i = 0; i < len; i++) {
arr[i] = createComplex(0, 0);
for (var n = 0; n < len; n++) {
var theta = pi2 * i * n * invlen;
var costheta = Math.cos(theta);
var sintheta = Math.sin(theta);
arr[i].real += samples[n].real * costheta - samples[n].imag * sintheta;
arr[i].imag += samples[n].real * sintheta + samples[n].imag * costheta;
}
if (!inverse) {
arr[i].real *= invlen;
arr[i].imag *= invlen;
}
}
return arr;
}
@AnastasiaDunbar
Copy link

Isn't the inverse supposed to be multiplied by 1/samples.length?

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