FORTRAN 90+: COMPLEX NUMBERS
Complex numbers are very important in engineering processes. Complex numbers, consisting of real and imaginary components describe, for example, the amplitude and phase (time lag) of the number for time dependent motion. Complex numbers have their own variable declaration type, COMPLEX, however, a complex number is described with both numbers, and so care must be taken in working with them.
First, many intrinsic functions are designed for real numbers, and they cannot be used with complex numbers. Instead, either the complex version of the intrinsic function should be used, such as the intrinsic function for the square root, SQRT, which becomes CSQRT for complex numbers. If the function does not have a complex counterpart, then the complex number should be broken into two components by taking the real and the imaginary components separately, and then performing the function on each number individually - IF it does not compromise the mathematical function. An example of this is SIGN(r), where the sign can be determined from the real and imaginary components individually. The list of intrinsic functions of the compiler should be examined to determine the availability of the various functions.
The two components can be easily extracted by the REAL(c) and AIMAG(c) intrinsic functions where c is the complex number.
Consider the classic case of the square root of -1. The root of -1. is i (or sometimes the integer j is used). To compute this value, the following program is proposed:
PROGRAM complex1 IMPLICIT NONE COMPLEX :: x REAL :: m1 m1 = 1.0 x = SQRT(m1) WRITE(*,*) REAL(x), AIMAG(x) END PROGRAM complex1
Note that x is defined as a complex number, and the output is written in two parts for the real and imaginary values expected. However, when this is run, an error is generated:
Runtime Error: *** Arithmetic exception: Floating invalid operation - aborting Abort trap
The problem is that the complex version of SQRT is needed:
PROGRAM complex1 IMPLICIT NONE COMPLEX :: x COMPLEX, PARAMETER :: m1=(-1.0, 0.0) x = CSQRT(m1) WRITE(*,*) REAL(x), AIMAG(x) END PROGRAM complex1
When this program is run, the result is:
0.0000000 0.9999999
which is, taking into account round-off errors is 0 + i or simply i, as expected.
It is clear that care must be taken with complex numbers.