The Azimuth Project
Complex arithmetic

Contents

Idea

This page is about numerical aspects of complex arithmetic. A lot of numerical algorithms need complex numbers, and most object oriented programming languages like Java or Scala don’t come with an implementation of complex numbers, or, like C++, sometimes come with suboptimal implementations. This page explains how complex arithmetic needs to be implemented to avoid common trap doors.

Details

Radius

If the radius r=zr = \| z \| of a complex number z=x+iyz = x + i \; y is calculated in the naive way

r=x 2+y 2 r = \sqrt{x^2 + y^2}

we’d get an overflow if xx or yy is bigger than the square root of the biggest representable number. This is an unnecessary overflow, since rr may be representable. A simple shuffling of terms avoids this:

r={|x|1+y 2x 2 for|x||y| |y|1+x 2y 2 for|y||x| r = \begin{cases} | x | \sqrt{1 + \frac{y^2}{x^2}} \; & \text{for} \; |x| \ge |y| \\ | y | \sqrt{1 + \frac{x^2}{y^2}} \; & \text{for} \; |y| \ge |x| \end{cases}

Division

Dividing two complex numbers could lead to unwanted overflows as well, this can be avoided by this implementation:

a+ibc+id={a+b(dc)+i[badc]c+d(dc) for|c||d| a(cd)+b+i[bcda]c(cd)+d for|c|<|d| \frac{a + i b}{c + i d} = \begin{cases} \frac{a+ b (\frac{d}{c}) + i [b - a \frac{d}{c}]}{c + d (\frac{d}{c})} \; & \text{for} \; |c| \ge |d| \\ \frac{a (\frac{c}{d}) + b + i [b \frac{c}{d} - a ]}{c (\frac{c}{d}) + d } \; & \text{for} \; |c| \lt |d| \; \end{cases}

References

  • William H. Press, Saul A. Teukolsky, William T. Vetterling, Brian P. Flannery: Numerical Recipes, The Art of Scientific Computing (3rd edition, chapter 5.5, webpage, ZMATH)