Gfortran and Complex Numbers

Gfortran's approach to complex arithmetic is to promote to the complex type in a mixed expression, and then to use the obvious full complex-complex formulae complete with IEEE-754. This is certainly compliant with the Fortran Standard, but not required by it.

Disadvantages of this approach include slow real by complex multiplication, and slow complex by real division. It can lead to surprises when multiplying by one:

  1*cmplx(Inf,0)=(Inf,NaN)
  1*cmplx(0,NaN)=(NaN,NaN)
  1*cmplx(0,-0)=(0,0)

It also means that the compiler cannot optimise away multiplications by one or additions of zero.

An advantage over C99's Annex G is that adding a real number can be fast, in that it is clear the 1+z means (1,0)+z. The latter vectorises much more easily than any attempt to avoid touching the imaginary part of z as Annex G requires. Touching the imaginary part of z could upset its sign if it were -0. Gfortran guarantees the following behaviour.

  sqrt(cmplx(-1.0,-0.0))     = (0.0,-1.0)
  sqrt(cmplx(-1.0+0.0,-0.0)) = (0.0,-1.0)
  sqrt(cmplx(-1.0,-0.0)+0.0) = (0.0,+1.0)

Annex G guarantees that all of the above evaluate to -i. The Fortran Standard does not define the sign of i in the third case, and one might argue about whether it does in the other two cases.

Note that when Gfortran and Annex G both define precise behaviour, they do not always define the same precise behaviour.