How to use complex number “i” in C++

后端 未结 6 838
暗喜
暗喜 2021-02-06 08:19

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 and #include&

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-06 08:54

    The following code in C++ shows a macro for implementing the imaginary number j. It is well known that in programming the terms i and j are commonly used as counter variables. I instead use the capital letter J to represent the imaginary number to avoid any confusion.

    / * dcomplex.h

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

    Using this macro, the imaginary number J [together with the complex library] can be used in the main code. An example of its use is shown below:

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

    ....

    where tmp, t[n] are variables of a complex type, and J is the imaginary number. The variables n, l, and tab_size are of an integer type. The constant PI is the well known constant 3.14... The function exp() is overloaded to handled complex numbers. [n.b. this code sample is part of a simple DFT]

    Using this macro, the code is more readable..

提交回复
热议问题