Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // fourier.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <fstream>
- #include <vector>
- #include <iostream>
- #include <math.h>
- # define M_PI 3.14159265358979323846
- void dump_to_file(const std::vector<double>& vec)
- {
- std::ofstream file;
- file.open("output.txt");
- for (auto item : vec)
- {
- file << item << std::endl;
- }
- file.close();
- }
- // Pass the input vector, as well as references to target vectors
- void dft(const std::vector<double>& input, std::vector<double>& real_output, std::vector<double>& imaginary_output)
- {
- int N = input.size();
- // Pre-resize our vectors so we don't reallocate memory by pushing every time
- real_output.resize(N/2);
- imaginary_output.resize(N/2);
- // For output X_k from k = 0 to N/2
- for (int k = 0; k < N/2; k++)
- {
- // Fake complex numbers lul
- double real_sum = 0;
- double imaginary_sum = 0;
- // Iterate over input elements X_n from n = 0 to N/2
- for (int n = 0; n < N; n++)
- {
- double angle = 2 * M_PI * k * n / N;
- real_sum += input[n] * std::cos(angle);
- imaginary_sum += input[n] * std::sin(angle);
- }
- real_output[k] = real_sum;
- imaginary_output[k] = imaginary_sum;
- }
- }
- int main()
- {
- std::ifstream file;
- file.open("1.txt");
- std::vector<double> input;
- int trash;
- double buffer;
- while (!file.eof())
- {
- // Discard the item number and read the signal value
- file >> trash >> buffer;
- input.push_back(buffer);
- }
- std::vector<double> real;
- std::vector<double> imaginary;
- dft(input, real, imaginary);
- // Combine into a modulus vector
- std::vector<double> output(real.size());
- for (int i = 0; i < output.size(); i++)
- {
- output[i] = sqrt(real[i] * real[i] + imaginary[i] * imaginary[i]);
- }
- // Dump to file
- dump_to_file(output);
- std::cout << real[0];
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement