[英]Segmentation fault when trying to do a descrete Fourier Transform with complex numbers
我試圖用 C++ 編寫一個 DFT 函數。 此函數將采用復數向量,應用 DFT,然后返回另一個復數向量。 然后我嘗試從我的計算機中讀取文件,應用該函數,然后將結果寫入其他文件。 當我運行它時,我遇到了分段錯誤。 按照本站點中的第一條評論( C++ 中的 Segmentation fault (core dumped) Can't find error ),我將 gdb 運行到代碼中,然后它返回了這個:
Program received signal SIGSEGV, Segmentation fault.
0x0000555555557088 in std::complex<double>::__rep (this=0x0) at /usr/include/c++/10/complex:1363
1363 _GLIBCXX_CONSTEXPR _ComplexT __rep() const { return _M_value; }
然后我深入挖掘,發現我使用的編譯器 g++ 在 4.9 版中遇到了這個問題。 我檢查了我的,得到了這個:
g++ (Ubuntu 10.3.0-1ubuntu1) 10.3.0
這是代碼:
#include <bits/stdc++.h>
using namespace std;
const float pi = 3.14159265358979;
vector<complex<double>> dft(vector<complex<double>> x){
int N = x.size();
vector<complex<double>> X;
for (int k = 0; k < N; k++){
double re = 0;
double im = 0;
for (int n = 0; n < N; n++){
double phi = (2 * pi * k * n) / N;
re += x[n].real() * cos(phi);
im -= x[n].imag() * sin(phi);
}
complex<double> result (re, im);
X.push_back(result);
}
return X;
}
int main(){
string temp;
vector<complex<double>> x, y;
vector<complex<double>> result_x, result_y;
ifstream x_data, y_data;
x_data.open("x.txt", ios::in);
y_data.open("y.txt", ios::in);
ofstream res_x, res_y;
res_x.open("result_x.txt", ios::out | ios::app);
res_y.open("result_y.txt", ios::out | ios::app);
while(x_data >> temp){
float temp_0 = stof(temp);
complex<double> adder (temp_0, 0);
x.push_back(adder);
}
while (y_data >> temp){
float temp_0 = stof(temp);
complex<double> adder (temp_0, 0);
y.push_back(adder);
}
result_x = dft(x);
result_y = dft(y);
for (unsigned int k = 0; k <= result_x.size(); k++){
int freq = k;
float amp_x = abs(result_x[k]);
float phase_x = arg(result_x[k]);
float amp_y = abs(result_y[k]);
float phase_y = arg(result_y[k]);
res_x << "[" << freq << ", " << amp_x << ", " << phase_x << "]" << endl;
res_y << "[" << freq << ", " << amp_y << ", " << phase_y << "]" << endl;
}
x_data.close();
y_data.close();
res_x.close();
res_y.close();
cout << "DONE!" << endl;
return 0;
}
問題是您在 for 循環中使用了k <= result_x.size()
而不是k < result_x.size()
。 所以在最后一次迭代(當k = result_x.size()
)你得到result_x[k];
未定義行為result_x[k];
. 您可以通過將 for 循環修改為如下所示來解決此問題:
for (unsigned int k = 0; k < result_x.size(); k++){//note i've used < instead of <=
//...other code here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.