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

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

+4
source share
5 answers

Here is a short example:

 #include <iostream> #include <complex> #include <cmath> using namespace std; typedef complex<double> dcomp; 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; } 

Tested with g ++

+4
source

I recently asked this question and found an easy way for the future reader:

Just use the <complex> library as shown below.

 #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) ; } 
+5
source

You can find the details here.

A simple approach would be

 #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 } 
+3
source

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

/ * dcomplex.h

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

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

 .... .... #include <complex> #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, J is an imaginary number. The variables n, l, and tab_size are of integer type. The constant PI is a well-known constant 3.14 ... The function exp () is overloaded into processed complex numbers. [Notabene, this sample code is part of a simple DFT]

Using this macro, the code is more readable.

+1
source

pi, which is an irrational number, cannot be exactly represented by double . cos of the inaccurate approximation pi is likely to produce a result close to, but possibly not exactly 1. Similarly, sin of the inaccurate approximation of the inaccurate approximation pi as the result has a very small value, which may not be exactly 0. Why not just determine that I am std :: complex (0.0, 1.0) and avoid irrevocable inaccuracy.

0
source

Source: https://habr.com/ru/post/1494066/


All Articles