Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- #include <cmath>
- #include <fstream>
- #include <string>
- #include <complex>
- #include <vector>
- using namespace std;
- double signal(double t, double T)
- {
- const double A = 1.0;
- const double f = 20.0;
- const double phi = M_PI / 2;
- return A * sin(2.0 * M_PI * f * t + phi);
- }
- double* generateSignal(int T)
- {
- auto tabSignal = new double[T];
- for (int i = 0; i < T; i++) {
- tabSignal[i] = i / (double) T;
- }
- return tabSignal;
- }
- vector<double> dff(double* signal, int N)
- {
- vector<double> results;
- for (int i = 0; i < N / 2; i++) {
- complex<double> sum = 0;
- complex<double> e(cos(-2 * M_PI * i / N), sin(-2 * M_PI * i / N));
- for (int j = 0; j < N; j++) {
- complex<double> x1(cos(-2 * M_PI * i * j / N), sin(-2 * M_PI * i * j / N));
- x1 = signal[j] * x1;
- sum += x1;
- }
- results.push_back(abs(sum));
- }
- return results;
- }
- vector<double> fft(double* signal, int N)
- {
- vector<double> results;
- for (int i = 0; i < N / 2; i++) {
- complex<double> sum1 = 0;
- complex<double> sum2 = 0;
- complex<double> e(cos(-2 * M_PI * i / N), sin(-2 * M_PI * i / N));
- for (int j = 0; j < N / 2; j++) {
- double k = i;
- double n = 2 * j;
- complex<double> x(cos(-2 * M_PI * k * n / N), sin(-2 * M_PI * k * n / N));
- x = signal[(int) n] * x;
- sum1 = sum1 + x;
- }
- for (int j = 0; j < N / 2; j++) {
- double k = i;
- double n = 2 * j + 1;
- complex<double> x(cos(-2 * M_PI * k * n / N), sin(-2 * M_PI * k * n / N));
- x = signal[(int) n] * x;
- sum2 = sum2 + x;
- }
- results.push_back(abs(sum1) + abs(e * sum2));
- }
- return results;
- }
- void signalToFile(const string& filePath, double* signal, int N)
- {
- fstream file(filePath, ios::out);
- if (!file.good()) {
- cerr << "ERROR: Cannot write to file " << filePath << endl << endl;
- return;
- }
- for (int i = 0; i < N; i++) {
- file << signal[i] << endl;
- }
- file.close();
- }
- void signalToFile(const string& filePath, vector<double>& signal)
- {
- fstream file(filePath, ios::out);
- if (!file.good()) {
- cerr << "ERROR: Cannot write to file " << filePath << endl << endl;
- return;
- }
- for (auto & it : signal) {
- file << fixed << it << endl;
- }
- file.close();
- }
- int main()
- {
- int T = 1000;
- double* signal = generateSignal(T);
- vector<double> fftSpectrum = fft(signal, T);
- signalToFile("signal.txt", signal, T);
- signalToFile("spectrum.txt", fftSpectrum);
- delete[] signal;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement