dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Sep 26, 2006

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Using Complex Numbers

The C++ standard library can handle complex numbers. Complex numbers may be used by including <complex>. The class std::complex is defined as a template, allowing complex numbers to use different value types, such as float and double.

You can construe complex numbers using the real and imaginary components; you can also construe them using the polar() function. For example:


std::complex<float> cf(1); // 1 + 0i
std::complex<double> cd(2, 3); // 2 + 3i
std::complex<long double> cld =
    std::polar<long double>(4, 5); // 4 e^(5i)
Obtain the magnitude, argument, and square of the magnitude using the abs(), arg(), and norm() member functions. For example:

std::cout << cd.abs() << ' '
          << cd.arg() << ' '
          << cd.norm() << std::endl;
Read complex numbers from std::cin and write them to std::cout. For example:

std::cin >> cd;
std::cout << cd << std::endl;
Complex numbers may be in the following three formats for std::cin:
  • 1 (meaning 1 + 0i)
  • (2) (meaning 2 + 0i)
  • (3,4) (meaning 3 + 4i)
Ignore any whitespace during input. Complex numbers are always output in the third format by std::cout.

Arithmetic operators such as +, -, *=, and /= work as expected for complex numbers. So do transcendental functions such as sin, cosh, exp, log, pow, and sqrt.

Kevin Spiteri
 
Thanks for your registration, follow us on our social networks to keep up-to-date