C++ “如何使用复数”;我";在C++;
我现在正在编写一个简单的DFT算法,我想在复指数中使用复数I。我看到有人使用了C++ “如何使用复数”;我";在C++;,c++,overloading,complex-numbers,complextype,C++,Overloading,Complex Numbers,Complextype,我现在正在编写一个简单的DFT算法,我想在复指数中使用复数I。我看到有人使用了#include和#include,然后他们使用了重载符号I,比如exp(2*I)。但在我的VisualStudio编译器中它似乎不起作用。那么,有谁能给出一个使用复指数的简单例子吗?谢谢 您可以找到详细信息 一个简单的方法是 #include <complex> using std::complex; const double pi = 3.1415; void foo() { complex&
#include
和#include
,然后他们使用了重载符号I
,比如exp(2*I)
。但在我的VisualStudio编译器中它似乎不起作用。那么,有谁能给出一个使用复指数的简单例子吗?谢谢 您可以找到详细信息
一个简单的方法是
#include <complex>
using std::complex;
const double pi = 3.1415;
void foo()
{
complex<double> val(polar(1, pi/2.0); Create a complex from its olar representation
}
#包括
使用std::complex;
常数双pi=3.1415;
void foo()
{
复数val(极坐标(1,pi/2.0);从其极坐标表示创建复数
}
以下是一个简短完整的示例:
#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
typedef complex<double> dcomp;
int main() {
dcomp i;
dcomp a;
double pi;
pi = 2 * asin(1);
i = -1;
i = sqrt(i);
a = exp(2*pi*i);
cout << "i is " << i << "and Euler was right: e(i pi) = " << a << endl;
}
#包括
#包括
#包括
使用名称空间std;
typedef复合dcomp;
int main(){
dcomp i;
dcomp a;
双pi;
pi=2*asin(1);
i=-1;
i=sqrt(i);
a=exp(2*pi*i);
在C++中,下面的代码显示了一个用于实现虚数J的宏。众所周知,在编程中,I和J通常用作反变量。我用大写字母J表示虚数,以避免混淆。< / P>
/*dcomplex.h
#ifndef DCOMPLEX_H_
#define DCOMPLEX_H_
#define J dcomplex(0.0,1.0)
typedef std::complex<double> dcomplex;
#endif /* DCOMPLEX_H_ */
\ifndef DCOMPLEX\u H_
#定义DCOMPLEX\u H_
#定义jdcomplex(0.0,1.0)
typedef std::复杂数据复杂;
#endif/*DCOMPLEX\u\H*/
使用此宏,可以在主代码中使用虚数J[连同复数库]。其使用示例如下所示:
....
....
#include <complex>
#include "dcomplex.h"
....
....
tmp = tmp + t[n]*exp( (2.0*PI*(double)n*(double)l/(double)tab_size)*J );
....
。。。。
....
#包括
#包括“dcomplex.h”
....
....
tmp=tmp+t[n]*exp((2.0*PI*(双)n*(双)l/(双)制表符大小)*J);
....
其中,tmp,t[n]是复数类型的变量,J是虚数。变量n,l和tab_size是整数类型。常数PI是众所周知的常数3.14…函数exp()重载为处理复数。[n.b.此代码示例是简单DFT的一部分]
使用此宏,代码更具可读性。我最近也遇到了这个问题,并为未来的读者找到了一个简单的方法:
只需像下面这样使用
库
#include <iostream>
#include <complex>
using namespace std ;
int main(int argc, char* argv[])
{
const complex<double> i(0.0,1.0);
cout << i << endl ;
return(0) ;
}
#包括
#包括
使用名称空间std;
int main(int argc,char*argv[])
{
常数复合物i(0.0,1.0);
coutpi是一个无理数,不能用pi的不精确近似的doublecos精确表示,它很可能产生接近但可能不完全为1的结果。同样地,pi的不精确近似的不精确近似的sin也会导致麻木er is的大小很小,可能不完全是0。为什么不将I定义为std::complex(0.0,1.0)并避免不必要的不精确性。另一种方法是在C++14之后使用:
#include <iostream>
#include <complex>
int main() {
using namespace std::complex_literals;
auto c = 1.0 + 3.0i;
std::cout << "c = " << c << '\n';
}
您可以创建一个复杂变量,并为其赋值sqrt(-1)但是,我真的很好奇,是否存在这样一个方便的重载符号。我是说那些创建C++的人应该考虑过它,对吗?good@Cancan:这个符号应该是一个复数
,复数
或复数
?;)顺便说一下,复数{0,1}
也很好。@Floris,很抱歉再问一个问题。你知道我应该添加哪个库来使用复数sqrt吗?我的编译器似乎总是告诉我有几个重载函数sqrt的实例。@Cancan-看看我的答案。按照我将I
定义为复数的方式,将值设置为-1
,然后调用e> sqrt
,我确保将调用正确版本的sqrt
。仅调用sqrt(-1)
不会自动为您获取正确版本的sqrt
,我在最初的评论中应该更清楚。
c = (1,3)