Created
December 4, 2014 01:11
-
-
Save shovon/c3ca8e59a5cf277c947a to your computer and use it in GitHub Desktop.
Discrete Fourier Transform in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Isn't the inverse supposed to be multiplied by
1/samples.length
?