Guest User

fourier c++

a guest
Jan 30th, 2023
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. /*by
  2. Kostanski Grzegorz
  3.  
  4. */
  5. #include <iostream>
  6. #include <complex>
  7. #include <math.h>
  8. #include <vector>
  9. #include <iomanip>
  10. #include <valarray>
  11. #define USE MATH DEFINES
  12. const double M_PI = acos(-1);
  13. using namespace std;
  14. typedef complex<double> Complex;
  15. typedef valarray<Complex> CArray;
  16. //const complex<double> I(0, 1);
  17.  
  18. vector<Complex> createSignal(){
  19. int N = 8;
  20. vector<Complex> signal;
  21. signal.reserve(N);
  22. double sigK = 3.0;
  23. double sigPhase = M_PI / 4.0;
  24. for (int x = 0; x < N; x++) {
  25. auto currentSample = Complex(cos((2 * M_PI / static_cast<double>(N)) * sigK * static_cast<double>(x) + sigPhase), 0.0);
  26. signal.push_back(currentSample);
  27. }
  28. return signal;
  29. }
  30.  
  31. CArray convertSignal(vector<Complex> x){
  32. int n = x.size();
  33. CArray data(n);
  34. for (int i = 0; i < n; i++) {
  35. data[i] = x[i];
  36. }
  37. return data;
  38. }
  39.  
  40. vector<Complex> dft(vector<Complex> x) {
  41. int n = x.size(); int k = n;
  42. Complex intSum;
  43. vector<Complex> output;
  44. output.reserve(k);
  45. for (int i = 0; i < k; i++) {
  46. intSum = Complex(0, 0);
  47. for (int j = 0; j < n; j++) {
  48. double real = cos(((2 * M_PI) / n) * i * j);
  49. double imag = sin(((2 * M_PI) / n) * i * j);
  50. Complex w(real, imag);
  51. intSum += x[j] * w;
  52. }
  53. output.push_back(intSum);
  54. }
  55. return output;
  56. }
  57.  
  58. CArray fft(CArray& x){
  59. const size_t N = x.size();
  60. if (N <= 1) return x;
  61. // divide
  62. CArray even = x[slice(0, N / 2, 2)];
  63. CArray odd = x[slice(1, N / 2, 2)];
  64. fft(even);
  65. fft(odd);
  66. for (size_t k = 0; k < N / 2; ++k){ // combine
  67. Complex t = polar(1.0, -2 * M_PI * k / N) * odd[k];
  68. x[k] = even[k] + t;
  69. x[k + N / 2] = even[k] - t;
  70. }
  71. return x;
  72. }
  73.  
  74. double repair(double N) { //returns 2**x number
  75. double logr = log2(N);
  76. logr = int(logr);
  77. return pow(2, logr);
  78. }
  79.  
  80. int main()
  81. {
  82. vector<Complex> syg = createSignal();
  83. CArray csig = convertSignal(syg);
  84. syg = dft(syg);
  85. csig = fft(csig);
  86. cout << "dft" << endl;
  87. for (int i = 0; i < 8; i++) {
  88. cout << syg[i] << endl;
  89. }
  90.  
  91. cout << "fft" << endl;
  92.  
  93. for (int i = 0; i < 8; i++) {
  94. cout << csig[i] << endl;
  95. }
  96.  
  97.  
  98. return 1;
  99. }
  100.  
  101.  
  102.  
Advertisement
Add Comment
Please, Sign In to add comment