gpt4 book ai didi

c++ - 在 C++ 中给出错误结果的复数方程

转载 作者:行者123 更新时间:2023-11-27 23:21:49 27 4
gpt4 key购买 nike

您好,我得到了错误的预期结果,我认为这是对 std::complex 的影响,这是我根据 matlab 应该得到的结果如果你运行下面的代码,这就是结果 result我明白了,基本上一切都只是 NAN,我哪里出错了?

#include<cmath>
#include<complex>
#include<new>
#include<iostream>



int sign(double x){
if(x > 0) {
return 1;
}
else if(x < 0) {
return -1;
}
else {
return 0;
}
}

int main(){

double alpha = 1.8;
double beta = .35;
double sigma = 1;
double mu = 0.5;
double PI = 3.1416;
int N = 8192;
double h = 0.01;
std::complex<double>phi[N];
double* in_t2= new double[N];


double* abs_t = new double [N];
double* sign_t = new double [N];

std::complex<double> I(0,1);
double s = 0.01;

s = 1/(h*N);
std::cout<<s;
for (int i=1; i<=N; i++) {
in_t2[i-1] = 2*PI * (i - 1 - N/2)*s; // x1

}

for (int i = 0; i < N; i++){
abs_t[i] = std::abs(in_t2[i]);
}

for (int i = 0; i < N; i++){
sign_t[i] = sign(in_t2[i]);
}

for (int i = 0; i < N; i++){
//where i suspect the error is..


phi[i] = pow(abs_t[i],sign_t[i]);
}


for ( int i = 0; i< N; i++){
if (in_t2[i] == 0){
phi[i] = 0;
}
phi[i] = std::exp(phi[i]);
}


return 0;
}

最佳答案

std::pow 将返回传递给它的相同类型。

如果您需要从 std::pow() 返回一个 std::complex,您必须传递一个 std::complex 到函数。

你可以通过转换任何表达式轻松解决这个问题

pow( expression )

到:

pow( std::complex( expression ) )

关于c++ - 在 C++ 中给出错误结果的复数方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334970/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com