Search code examples
c++overloadingcomplex-numberscomplextype

How to use complex number "i" in C++


I am coding a simple DFT algorithm now and I want to use the complex number i in complex exponential. I saw somebody use #include<complex> and #include<cmath>, and then they used the overloaded symbol I such as exp(2*I) . But it seems it doesn't work in my visual studio compiler. So, can anyone give a simple example of using complex exponential? Thanks!


Solution

  • Here is a short complete example:

    #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(pi*i) + 1.+0i;
      cout << "i is " << i << "and Euler was right: exp(i pi) + 1 = " << a << endl;
    } 
    

    Tested with g++