8

我现在正在编写一个简单的 DFT 算法,我想在复指数中使用复数 i。我看到有人使用#include<complex>and #include<cmath>,然后他们使用了重载符号I,例如exp(2*I). 但它似乎在我的 Visual Studio 编译器中不起作用。那么,任何人都可以举一个使用复指数的简单例子吗?谢谢!

4

6 回答 6

11

我最近也收到了这个问题,并为未来的读者找到了一个简单的方法:

只需使用<complex>如下库

#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) ;
}
于 2015-09-15T23:55:12.580 回答
7

另一种方法是std::literals::complex_literals::operator""i在C++14之后使用:

#include <iostream>
#include <complex>

int main() {
    using namespace std::complex_literals;
    auto c = 1.0 + 3.0i;
    std::cout << "c = " << c << '\n';
}

输出:

c = (1,3)
于 2019-12-04T20:27:02.977 回答
6

这是一个简短的完整示例:

#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;
} 

用 g++ 测试

于 2013-07-29T14:10:26.383 回答
3

你可以在这里找到详细信息

一个简单的方法是

#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
}
于 2013-07-29T14:02:27.507 回答
1

以下 C++ 代码显示了用于实现虚数 j 的宏。众所周知,在编程中,术语 i 和 j 通常用作计数器变量。我改为使用大写字母 J 来表示虚数以避免任何混淆。

/ * dcomplex.h

#ifndef DCOMPLEX_H_
#define DCOMPLEX_H_
#define J dcomplex(0.0,1.0)
typedef std::complex<double> dcomplex;
#endif /* DCOMPLEX_H_ */

使用这个宏,虚数 J [连同复数库] 可以在主代码中使用。其使用示例如下所示:

....
....
#include <complex>
#include "dcomplex.h"

....
....
 tmp = tmp + t[n]*exp( (2.0*PI*(double)n*(double)l/(double)tab_size)*J );
....

……

其中 tmp, t[n] 是复数类型的变量,J 是虚数。变量 n、l 和 tab_size 是整数类型。常数 PI 是众所周知的常数 3.14... 函数 exp() 被重载以处理复数。[nb 此代码示例是简单 DFT 的一部分]

使用此宏,代码更具可读性..

于 2015-08-18T02:57:24.917 回答
0

pi是一个无理数,不能用double精确表示。 对 pi 的不精确近似的cos可能会产生接近但可能不完全为 1 的结果。同样,对pi的不精确近似的不精确近似的sin会导致一个数字的量级非常小,即也许不完全是 0。为什么不将 I 定义为std::complex(0.0, 1.0)并避免无缘无故的不精确。

于 2018-03-15T20:27:08.600 回答