Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*by
- Kostanski Grzegorz
- */
- #include <iostream>
- #include <complex>
- #include <math.h>
- #include <vector>
- #include <iomanip>
- #include <valarray>
- #define USE MATH DEFINES
- const double M_PI = acos(-1);
- using namespace std;
- typedef complex<double> Complex;
- typedef valarray<Complex> CArray;
- //const complex<double> I(0, 1);
- vector<Complex> createSignal(){
- int N = 8;
- vector<Complex> signal;
- signal.reserve(N);
- double sigK = 3.0;
- double sigPhase = M_PI / 4.0;
- for (int x = 0; x < N; x++) {
- auto currentSample = Complex(cos((2 * M_PI / static_cast<double>(N)) * sigK * static_cast<double>(x) + sigPhase), 0.0);
- signal.push_back(currentSample);
- }
- return signal;
- }
- CArray convertSignal(vector<Complex> x){
- int n = x.size();
- CArray data(n);
- for (int i = 0; i < n; i++) {
- data[i] = x[i];
- }
- return data;
- }
- vector<Complex> dft(vector<Complex> x) {
- int n = x.size(); int k = n;
- Complex intSum;
- vector<Complex> output;
- output.reserve(k);
- for (int i = 0; i < k; i++) {
- intSum = Complex(0, 0);
- for (int j = 0; j < n; j++) {
- double real = cos(((2 * M_PI) / n) * i * j);
- double imag = sin(((2 * M_PI) / n) * i * j);
- Complex w(real, imag);
- intSum += x[j] * w;
- }
- output.push_back(intSum);
- }
- return output;
- }
- CArray fft(CArray& x){
- const size_t N = x.size();
- if (N <= 1) return x;
- // divide
- CArray even = x[slice(0, N / 2, 2)];
- CArray odd = x[slice(1, N / 2, 2)];
- fft(even);
- fft(odd);
- for (size_t k = 0; k < N / 2; ++k){ // combine
- Complex t = polar(1.0, -2 * M_PI * k / N) * odd[k];
- x[k] = even[k] + t;
- x[k + N / 2] = even[k] - t;
- }
- return x;
- }
- double repair(double N) { //returns 2**x number
- double logr = log2(N);
- logr = int(logr);
- return pow(2, logr);
- }
- int main()
- {
- vector<Complex> syg = createSignal();
- CArray csig = convertSignal(syg);
- syg = dft(syg);
- csig = fft(csig);
- cout << "dft" << endl;
- for (int i = 0; i < 8; i++) {
- cout << syg[i] << endl;
- }
- cout << "fft" << endl;
- for (int i = 0; i < 8; i++) {
- cout << csig[i] << endl;
- }
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment