RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Complex Arithmetic Without Complexities-2 : Page 2

real and i
Real numbers are represented in C++ as floating point variables (float, double, and long double). The theory of complex numbers defines a superset of real numbers called complex numbers. A complex number is a composite number that consists of two units. The first one is called the real part and is denoted by a lowercase r. The unit part is the imaginary part and is denoted by a lowercase i. Just as the fractional part and the integral part of the number 10.34 make a single real number, the real and imaginary units are construed as a single complex number. A common way of representing a complex number is to pack two floating point variables in a struct. Problems start when you need to perform mathematical operations on such objects. The built-in operators of C++ +,-,/, etc. do not support an arbitrary user-defined complex number. Using complex numbers in C++ presents two problems:
  • The representation of a complex number
  • Arithmetic operations such as addition, multiplication, and division of complex numbers
The Standard Library header <complex> contains a mini-library for manipulating complex numbers easily. It includes the class template std::complex<T> which has three explicit specializations, one for every native floating type:
  • std::complex<float>
  • std::complex<double>
  • std::complex<long double>
First, decide which of these three specializations suits your needs best. std::complex<float> is the most compact, occupying eight bytes per one complex number. Alas, it also has the lowest precision and cannot represent real or imaginary values that are higher than numeric_limits<float>::max(). std::complex<double> is a reasonable compromise between space usage (16 bytes per object) and precision. std::complex<long double> offers the highest precision but also uses 20 bytes (at least) per complex number.

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