C++ Complex Number — 02
Date: 2023-03-10Last modified: 2023-03-22
CC-BY-SA-3.0 diagram by Daniele Pugliesi on Wikimedia
Table of contents
const double Fs = 1000.0; // Sampling frequency (Hz)
const int N = 1024; // signal length
std::vector<double> signal(N); // time-domain signal
std::vector<std::complex<double>> spectrum(N); // frequency-domain spectrum
// fill signal with data...
for (int n = 0; n < N; n++) {
signal[n] = 10 * std::sin(2 * M_PI * 25 * n / Fs) +
20 * std::sin(2 * M_PI * 50 * n / Fs) +
30 * std::sin(2 * M_PI * 100 * n / Fs);
}
// create FFTW plan
fftw_plan plan = fftw_plan_dft_r2c_1d(
N, signal.data(), reinterpret_cast<fftw_complex*>(spectrum.data()),
FFTW_ESTIMATE);
// perform FFT
fftw_execute(plan);
// destroy plan
fftw_destroy_plan(plan);
for (int i = 0; i < N / 2 + 1; i++) {
auto norm = abs(spectrum[i]);
if (norm > 3000) {
double freq = i * Fs / N;
fmt::print(
"Freq: {:5.1f} Norm: {:7.1f} Complex: {:7.1f} + {:7.1f}i\n", freq,
norm, spectrum[i].real(), spectrum[i].imag());
}
}
Possible output
Freq: 25.4 Norm: 3741.2 Complex: -3524.0 + -1256.2i
Freq: 49.8 Norm: 9643.3 Complex: 5698.9 + -7779.3i
Freq: 98.6 Norm: 3290.9 Complex: 3138.5 + -989.8i
Freq: 99.6 Norm: 11594.9 Complex: 11036.1 + -3556.3i
Freq: 100.6 Norm: 7779.4 Complex: -7390.0 + 2430.3i