[英]equation with complex numbers giving wrong result in c++
Hi I'm getting the wrong expected result and I think it's do to std::complex, heres the result I should be getting according to matlab and here's the result if you run the code below this is the result i get , basically everything is just NAN, where did i go wrong? 嗨,我得到了错误的预期结果,我认为这是对std :: complex的影响,这是我应该根据matlab得到的结果,如果您在下面运行代码,这就是结果 ,这就是我得到的结果 ,基本上是只是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;
}
The pow
function called here pow
函数在这里调用
pow((-1.0*abs_t[i]), alpha)
is the one for double
arguments and results, which returns a NaN for negative bases. 是用于double
参数和结果的值,对于负底数返回NaN。
std::pow
will return the same type that is passed to it. std::pow
将返回传递给它的相同类型。
If you need a std::complex
to be returned from std::pow()
, you must pass a std::complex
to the function. 如果您需要std::complex
从返回std::pow()
您必须通过std::complex
的功能。
You can easily solve this by casting any expression 您可以通过强制转换任何表达式来轻松解决此问题
pow( expression )
to: 至:
pow( std::complex( expression ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.