Last active
August 22, 2021 16:13
-
-
Save wobbol/7d2df4490704ea7d9f7340adca35c058 to your computer and use it in GitHub Desktop.
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
/* $(CC) dft_example.c -lm -g -Wall */ | |
#include <stdio.h> | |
#include <complex.h> | |
#include <math.h> | |
#define BUCKETS 16 | |
/* | |
* XXX: looses any phase information. | |
* len samples go in and len freqs come out. | |
*/ | |
void dft(int *samples, int *freqs, int len) { | |
for(int i = 0; i < len; i++) { | |
for(int j = 0; j < len; j++) { | |
freqs[i] += samples[j] * cexp((- I * 2 * M_PI * i * j)/len); | |
} | |
} | |
} | |
/* | |
* XXX: looses any phase information. | |
* len freqs go in and len samples come out. | |
* */ | |
void inv_dft(int *freqs, int *samples, int len) { | |
for(int i = 0; i < len; i++) { | |
for(int j = 0; j < len; j++) { | |
samples[i] += freqs[j] * cexp(( I * 2 * M_PI * i * j)/len); | |
} | |
samples[i] = samples[i]/len; | |
} | |
} | |
int main(void) { | |
int samples[BUCKETS] = {0}; | |
int freqs[BUCKETS] = {0}; | |
float peak = 2; | |
for(int i = 0; i < BUCKETS; i++) { | |
samples[i] = 128*sin(i/((float)BUCKETS)*2.0 * M_PI * peak); | |
} | |
//freqs[2] = 128; | |
//inv_dft(freqs, samples, BUCKETS); | |
dft(samples, freqs, BUCKETS); | |
puts("samples"); | |
for(int i = 0; i < BUCKETS; i++) { | |
printf("%d\n", samples[i]); | |
} | |
puts("freqs"); | |
for(int i = 0; i < BUCKETS; i++) { | |
printf("%d\n", freqs[i]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment