DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Complex arithmetic in C++

Complex arithmetic in C++

This topic describes a data type complex providing the basic facilities for using complex arithmetic in C++. The usual arithmetic operators can be used on complex numbers and a library of standard complex mathematical functions is provided. For example:
   #include <complex.h>
   

main(){ complex xx; complex yy = complex(1,2.718); xx = log(yy/3); cout << 1+xx; }

initializes yy as a complex number of the form (real+imag*i), evaluates the expressions and prints the result: (0.96476,1.21825).

The C++ language does not have a built-in data type for complex numbers, but it does provide language facilities for defining new data types. The type complex is an example of how such a type is as easy to use, and almost as efficient, as a built-in type.

This facility for complex arithmetic provides the arithmetic operators +, /, *, and -, the assignment operators =, +=, -=, *=, and /=, and the comparison operators == and != for complex numbers. Expressions such as (xx+1)*log(yy*log(3.2)) that involve a mixture of real and complex numbers are handled correctly. The simplest complex operations, for example + and +=, are implemented without function call overhead. Input and output can be done using the operators >> (get from) and << (put to). The initialization functions and >> accept a Cartesian representation of a complex. The functions real() and imag() return the real and imaginary part of a complex, respectively, and << prints a complex as (real,imaginary). The internal representation of a complex, is, however, inaccessible and in principle unknown to a user.

Polar coordinates can also be used. The function polar() creates a complex given its polar representation, and abs() and arg() return the polar magnitude and angle, respectively, of a complex. The function norm() returns the square of the magnitude of a complex. The following complex functions are also provided: sqrt(), exp(), log(), sin(), cos(), sinh(), cosh(), pow(), and conj().

A complete program using complex numbers can be found under ``An FFT function''

The complex type described in this topic is similar, but not identical, to the double_complex type being specified in the upcoming ANSI/ISO C++ language standard. In particular, unlike the upcoming standard, no complex type is defined for float or long double types.


Next topic: Complex variables and data initialization

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004