Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. // fourier.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <fstream>
  6. #include <vector>
  7. #include <iostream>
  8. #include <math.h>
  9.  
  10. # define M_PI 3.14159265358979323846
  11.  
  12. void dump_to_file(const std::vector<double>& vec)
  13. {
  14.     std::ofstream file;
  15.     file.open("output.txt");
  16.     for (auto item : vec)
  17.     {
  18.         file << item << std::endl;
  19.     }
  20.     file.close();
  21. }
  22.  
  23. // Pass the input vector, as well as references to target vectors
  24. void dft(const std::vector<double>& input, std::vector<double>& real_output, std::vector<double>& imaginary_output)
  25. {
  26.     int N = input.size();
  27.  
  28.     // Pre-resize our vectors so we don't reallocate memory by pushing every time
  29.     real_output.resize(N/2);
  30.     imaginary_output.resize(N/2);
  31.  
  32.     // For output X_k from k = 0 to N/2
  33.     for (int k = 0; k < N/2; k++)
  34.     {
  35.         // Fake complex numbers lul
  36.         double real_sum = 0;
  37.         double imaginary_sum = 0;
  38.  
  39.         // Iterate over input elements X_n from n = 0 to N/2
  40.         for (int n = 0; n < N; n++)
  41.         {
  42.             double angle = 2 * M_PI * k * n / N;
  43.            
  44.             real_sum += input[n] * std::cos(angle);
  45.             imaginary_sum += input[n] * std::sin(angle);
  46.         }
  47.  
  48.         real_output[k] = real_sum;
  49.         imaginary_output[k] = imaginary_sum;
  50.     }
  51. }
  52.  
  53. int main()
  54. {
  55.     std::ifstream file;
  56.     file.open("1.txt");
  57.  
  58.     std::vector<double> input;
  59.     int trash;
  60.     double buffer;
  61.     while (!file.eof())
  62.     {
  63.         // Discard the item number and read the signal value
  64.         file >> trash >> buffer;
  65.         input.push_back(buffer);
  66.     }
  67.  
  68.     std::vector<double> real;
  69.     std::vector<double> imaginary;
  70.  
  71.     dft(input, real, imaginary);
  72.  
  73.     // Combine into a modulus vector
  74.     std::vector<double> output(real.size());
  75.    
  76.     for (int i = 0; i < output.size(); i++)
  77.     {
  78.         output[i] = sqrt(real[i] * real[i] + imaginary[i] * imaginary[i]);
  79.     }
  80.  
  81.     // Dump to file
  82.     dump_to_file(output);
  83.  
  84.     std::cout << real[0];
  85.  
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement