Complex numbers in C++

This web page gives a brief introduction to using complex numbers in C++. Of course we give very few details, and for more information you must read further technical documentation, e.g. at http://www.cplusplus.com/reference/complex/.

C++ provides the notion of a complex number based on another type. Thus usual complex numbers are based on double and the corresponding type is called std::complex<double>. Also it is necessary to #include <complex> and to avoid having to write std:: all the time a "using" statements such as using namespace std; can be used.

Here is a sample program.

// complexarith.cpp (click here to download)

// Program that illustrates complex numbers
#include <iostream>
#include <complex>

using namespace std;

int main() {
  complex<double> x,y,z;
  complex<double> i(0.0,1.0); // initialise i = sqrt(-1)
  cout << "Please think of a complex number." << endl;
  cout << "What is your number?" << endl;
  cin >> x;
  y = x * x + 1.0 + i; // complex arithmetic, note doubles are converted to complex
  z = y + complex<double>(2.0,3.0); // how you represent an arbitrary complex
  cout << "The number you thought of was x = " << x << endl;
  cout << "x * x + 1.0 + i = " << y << endl;
  cout << "x * x + 1.0 + i + (2.0,3.0) = " << z << endl;
  return 0;
}

For input/output, a complex number x + i y is written as (x,y). You can type your input number in this style, or else standard real (i.e. double) constants are also accepted. As you can see, all the standard arithmetic operations are supported, and doubles are converted to complex values where needed.

C++ overloads the standard math functions to work for complex, as you might hope. Here is a number of the functions available.

double real(complex<double> x); // real part
double imag(complex<double> x); // imaginary part
double arg(complex<double> x); // argument, -pi/2..pi/2
double abs(complex<double> x); // modulus
double norm(complex<double> x); // square of modulus
complex<double> conj(complex<double> x); // conjugate
complex<double> polar(double r, double theta); // convert polar form to complex
complex<double> cos(complex<double> x); // cos of x
complex<double> cosh(complex<double> x); // hyperbolic cos of x
complex<double> exp(complex<double> x); // e to the x
complex<double> log(complex<double> x); // natural log of x
complex<double> log10(complex<double> x); // base 10 log of x
complex<double> pow(complex<double> x, complex<double> y); // x to the y
complex<double> sin(complex<double> x); // sin of x
complex<double> sinh(complex<double> x); // hyperbolic sin of x
complex<double> sqrt(complex<double> x); // square root of x
complex<double> tan(complex<double> x); // tan of x
complex<double> tanh(complex<double> x); // hyperbolic tan of x