forked from 1chipML/1chipML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFT.c
48 lines (42 loc) · 1.66 KB
/
DFT.c
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
48
#include "DFT.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
/**
* @param length The length of the input vectors.
* @param realArray 1D array containing the real part of the incoming vector.
* This array will contain the end result of the real part of the DFT
* @param imaginaryArray 1D array containing the imaginary part of the incoming
* vector. This array will contain the end result of the imaginary part of the
* DFT
* @param dir Direction of the DFT. 1 for the DFT, -1 for the inverse DFT
*/
void DFT(const unsigned length, dft_real* realArray, dft_real* imaginaryArray,
const int dir) {
dft_real outputReals[length];
dft_real outputImaginaries[length];
memset(outputReals, 0, length * sizeof(dft_real));
memset(outputImaginaries, 0, length * sizeof(dft_real));
int thetaFactor = dir < 0 ? 1 : -1;
for (unsigned i = 0; i < length; ++i) {
dft_real exponentBase = thetaFactor * 2.0 * M_PI * i / length;
for (unsigned k = 0; k < length; ++k) {
dft_real wCos = cos(k * exponentBase); // real part
dft_real wSin = sin(k * exponentBase); // imaginary part
outputReals[i] += realArray[k] * wCos - imaginaryArray[k] * wSin; // real
outputImaginaries[i] +=
realArray[k] * wSin + imaginaryArray[k] * wCos; // imaginary
}
}
// inverse DFT
if (dir < 0) {
const dft_real inverseLength = 1.0 / length;
for (unsigned i = 0; i < length; ++i) {
outputReals[i] *= inverseLength;
outputImaginaries[i] *= inverseLength;
}
}
// place result in arrays
memcpy(realArray, outputReals, length * sizeof(dft_real));
memcpy(imaginaryArray, outputImaginaries, length * sizeof(dft_real));
}