I am trying to do discrete Fourier transforms in C.
Initially just the brute-force method. First I had the program open a data file (of amplitudes) and put the data into an array (just one, since I'm limiting myself to real-valued input).
But the transform looked wrong, so instead I tried to generate a simple wavefunction and check whether it transforms properly.
Here's my code, stripped of the bells and whistles:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M_PI 3.14159265358979323846
//the test wavefunction
double theoretical(double t)
{
double a = sin(M_PI * t) + 2 * sin(2 * M_PI * t) + 4 * sin(4 * M_PI * t);
return a;
}
//-------------------------------------------------------------------------
void dftreal(double inreal[], double outreal[], double outimag[], int linecount)
{
int n, k;
for (k = 0; k < linecount; k++)
{
double sumreal = 0;
double sumimag = 0;
for (n = 0; n < linecount; n++)
{
double angle = 2 * M_PI * n * ( k / (double) linecount);
sumreal += inreal[n] * cos(angle);
sumimag += inreal[n] * sin(angle);
}
outreal[k] = sumreal;
outimag[k] = sumimag;
}
}
//=========================================================================
int main(void)
{
int linecount = 44100;
//creates all necessary arrays
double inreal[linecount], outreal[linecount], outimag[linecount], p[linecount];
FILE *fout = fopen("Output.txt", "w");
for (int i = 0 ; i < linecount ; ++i)
{
inreal[i] = theoretical( i / (double) linecount);
}
//actually computes the transform
dftreal(inreal, outreal, outimag, linecount);
for (int i = 0 ; i < linecount ; ++i)
{
p[i] = 2*(outreal[i] * outreal[i] + outimag[i] * outimag[i]);
fprintf(fout, "%f %f \n", (i / (double) linecount), p[i]);
}
fclose(fout);
printf("\nEnd of program");
getchar();
return 0;
}
The program compiles, completes, but instead of several sharp peaks on a power(frequency) plot, I get this: .
A single frequency or different frequencies give the exact same inverted-bathtub-curve.
I checked several sources about the DFT and I still don't know what is going wrong, there do not seem to be any glaring errors with the function:
dftreal
itself. I'd like to ask for help on what could be causing the issue. I'm using the MinGW compiler on Windows 7. Thanks!