DFT (discrete fourier transform) with C++ STL

Johannes picture Johannes · May 3, 2012 · Viewed 13.8k times · Source

I try to calculate the DFT for this array x_1. It must be dead simple, but my values are way too low. What's wrong with my code?

Please no links to other examples - just looking for a fix for my own code.

#include <iostream>
#include <complex>
#include <cassert>

int main ()
{
    const unsigned int N = 20;

    const double x_1[N] = {0, 0.3, 0.6, 0.8, 1, 1, 0.9, 0.7, 0.5, 0.2, 0.2, 0.5, 0.7, 0.9, 1, 1, 0.8, 0.6, 0.3, 0};

    for(unsigned int k = 0; k < N; k++)
    {
        std::complex<double> sum(0.0,0.0);
        for(unsigned int j = 0; j < N; j++)
        {
            int integers = -2*j*k;
            std::complex<double> my_exponent(0.0, M_PI/N*(double)integers);
            sum += x_1[j] * std::exp(my_exponent);
        }
        std::cout << abs(sum)/N << std::endl;
    }
    return 0;
} 

Answer

BertR picture BertR · May 3, 2012
std::cout << abs(sum)/N << std::endl;

Why are you dividing by N?

The coefficients are without the division. See the wiki.

These are the values I get with Matlab:

12.0000000000000 + 0.00000000000000i
-0.971586454726535 - 0.153884176858763i
-4.26246117974981 - 1.38495759172886i   
-0.0712959999079796 - 0.0363271264002681i   
-0.473606797749979 - 0.344095480117793i
0.00000000000000 + 0.00000000000000i
-0.237538820250189 - 0.326944137602412i
0.0185095954079375 + 0.0363271264002681i
-0.0263932022500213 - 0.0812299240582274i
0.0243728592265771 + 0.153884176858763i
0.00000000000000 + 0.00000000000000i    
0.0243728592265771 - 0.153884176858763i
-0.0263932022500213 + 0.0812299240582274i
0.0185095954079375 - 0.0363271264002681i    
-0.237538820250189 + 0.326944137602412i 
0.00000000000000 + 0.00000000000000i    
-0.473606797749979 + 0.344095480117793i 
-0.0712959999079796 + 0.0363271264002681i
-4.26246117974981 + 1.38495759172886i   
-0.971586454726535 + 0.153884176858763i

and I see more or less the same values when I print using std::cout << sum << std::endl;