Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 374
Cancan Avatar asked Jul 29 '13 13:07

Cancan


People also ask

What is imaginary in C?

In C, imaginary is a macro that enables the programmer to write pure imaginary numbers. The imaginary macro expands to the _Imaginary macro. To use the imaginary macro, the program needs to include the header file <complex.h> as shown below: #include <complex.h>

What is i in the complex number?

Complex Numbers in Maths. Complex numbers are the numbers that are expressed in the form of a+ib where, a,b are real numbers and 'i' is an imaginary number called “iota”. The value of i = (√-1). For example, 2+3i is a complex number, where 2 is a real number (Re) and 3i is an imaginary number (Im).


Video Answer


4 Answers

I get this question recently as well and find a easy way for future reader:

Just use <complex> library like the following

#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) ;
}
like image 61
Mike22LFC Avatar answered Oct 25 '22 13:10

Mike22LFC


Another way is to use std::literals::complex_literals::operator""i after C++14:

#include <iostream>
#include <complex>

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

Output:

c = (1,3)
like image 8
Ayxan Haqverdili Avatar answered Oct 25 '22 14:10

Ayxan Haqverdili


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++

like image 7
Floris Avatar answered Oct 25 '22 13:10

Floris


You can find 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
}
like image 3
ogni42 Avatar answered Oct 25 '22 13:10

ogni42