Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #include <fftw3.h>
  2.  
  3. #include <iostream>
  4.  
  5. // convenience macros for the real and imaginary parts
  6. constexpr int REAL = 0;
  7. constexpr int IMAG = 1;
  8. // length of the complex arrays
  9. constexpr int N = 8;
  10.  
  11. /* Computes the 1-D fast Fourier transform. */
  12. void fft(fftw_complex* in, fftw_complex* out)
  13. {
  14. // create a DFT plan
  15. fftw_plan plan = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
  16. // execute the plan
  17. fftw_execute(plan);
  18. // do some cleaning
  19. fftw_destroy_plan(plan);
  20. fftw_cleanup();
  21. }
  22.  
  23. /* Computes the 1-D inverse fast Fourier transform. */
  24. void ifft(fftw_complex* in, fftw_complex* out)
  25. {
  26. // create an IDFT plan
  27. fftw_plan plan = fftw_plan_dft_1d(N, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
  28. // execute the plan
  29. fftw_execute(plan);
  30. // do some cleaning
  31. fftw_destroy_plan(plan);
  32. fftw_cleanup();
  33. // scale the output to obtain the exact inverse
  34. for (int i = 0; i < N; ++i) {
  35. out[i][REAL] /= N;
  36. out[i][IMAG] /= N;
  37. }
  38. }
  39.  
  40. /* Displays complex numbers in the form a +/- bi. */
  41. void displayComplex(fftw_complex* y)
  42. {
  43. for (int i = 0; i < N; ++i) {
  44. if (y[i][IMAG] < 0) {
  45. std::cout << y[i][REAL] << " - " << abs(y[i][IMAG]) << "i" << std::endl;
  46. } else {
  47. std::cout << y[i][REAL] << " + " << y[i][IMAG] << "i" << std::endl;
  48. }
  49. }
  50. }
  51.  
  52. /* Displays the real parts of complex numbers. */
  53. void displayReal(fftw_complex* y)
  54. {
  55. for (int i = 0; i < N; ++i) {
  56. std::cout << y[i][REAL] << std::endl;
  57. }
  58. }
  59.  
  60. /* Test */
  61. int main()
  62. {
  63. // input array
  64. fftw_complex x[N];
  65. // output array
  66. fftw_complex y[N];
  67. // fill the first array with some numbers
  68. for (int i = 0; i < N; ++i) {
  69. x[i][REAL] = i + 1.; // i.e., { 1, 2, 3, 4, 5, 6, 7, 8 }
  70. x[i][IMAG] = 0;
  71. }
  72. // compute the FFT of x and store the results in y
  73. fft(x, y);
  74. // display the results
  75. std::cout << "FFT =\n";
  76. displayComplex(y);
  77. // compute the IFFT of y and store the results in x
  78. ifft(y, x);
  79. // display the results
  80. std::cout << "\nIFFT =\n";
  81. displayReal(x);
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement