# The Azimuth Project Complex arithmetic (changes)

Showing changes from revision #2 to #3: Added | Removed | Changed

# 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

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

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

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

$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:

$\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)