# Fortran/complex types

In mathematics, a complex number has a real and an imaginary component. In Fortran, complex numbers are stored as a pair of real numbers (real part first, followed by the imaginary part), or a pair of double-precision numbers.

For composite or structured data, see Structures.

## Declaration[edit]

The standard way to declare a complex number is simply using the `COMPLEX`

statement:

```
COMPLEX myVariable, anotherVariable, anArray(2,3)
```

This is equivalent on most systems to specifying a length of 8 (two 4-byte Reals):

```
COMPLEX*8 myVariable, anotherVariable, anArray(2,3)
```

If you want double-precision complex numbers, you're pretty much stuck with specifying a precision, and hoping that the compiler likes that format. Here's where portability comes in: If, for instance, the machine has floating point types of lengths 4, 8, and 16, and I specify a complex length of 8, 16, or 32, I'm likely to get a pair of floating point numbers at the size I expect. If, however, I specify a length of some other value, for instance, 10, then I'm likely to get a pair of 4s or 8s, depending on what the compiler likes to do. So, in general, to get the values as double-precision, I'd code:

```
COMPLEX*16 myVariable, anotherVariable, anArray(2,3)
```

## Constants and Expressions[edit]

Complex constants are specified as `(`

, a real value, a comma, another real value, and `)`

. Some examples are 1 as `(1.0,0.0)`

, *i* as `(0.0,1.0)`

, 2-3*i* as `(2.0,-3.0)`

, and 1000000000*i* as `(0.0,1.0E+09)`

. The same constants can be coded as double-precision complex constants by the simple expedient of using a `D`

in the exponent. Thus, the same constants can be coded in double-precision using `(1.0D+00,0.0D+00)`

, `(0.0D+00,1.0D+00)`

, `(2.0D+00,-3.0D+00)`

, and `(0.0D+00,1.0D+09)`

, respectively. Note: This notation cannot be used with variables. For example, `(a, b)`

is invalid. To convert real variables to complex, use the `CMPLX`

function:

```
CMPLX(a, b)
```

Any expression involving complex numbers and other numbers is promoted to complex.

## Operators and Functions[edit]

All of the arithmetic operators can take a complex number on either side.

Care must be taken in using function calls that might cause an error. For instance, taking the square root of the real number -1 (coded as `-1.0`

) will result in an error, because -1 is outside of the domain of real square root. Taking the square root of the complex number -1 (coded as `(-1.0,0.0)`

) is OK, because -1 is in the domain of complex square root.