Complex Numbers in Julia

Complex numbers are one of those topics a lot of people don't understand but are ridiculously powerful and have numerous applications in the real world, despite being called "imaginary numbers."

A complex number is a mathematical object of the form,

\[ z = a + ib\,, \]

where \(i = \sqrt{-1}\). Naturally, Julia offers great out-of-the-box support for complex numbers.

Complex numbers can be instantiated by using the Complex object or through the syntactic sugar a+bim where \(a\) and \(b\) are numerals.

Complex(3, 4) == 3+4im
> true

We can extract the real or imaginary parts using real and imag.

z = 3+4im
z == real(z) + imag(z)*im
> true

Computing the length or modulus of a complex number is done with the abs function.

Recall that the formula for the modulus of a complex number uses the Pythagorean theorem,

\[ |z| = \sqrt{\frak{Re}(z)^2 + \frak{Im}(z)^2}\,.\]
abs(z)
> 5.0

We can also compute the squared modulus more efficiently than if we were to square the result of abs with abs2

abs2(z)
> 25

We can compute the complex conjugate using conj.

conj(z)
> 3 - 4im

We can compute the angle between the real and imaginary components using angle and convert it from radians to degrees using rad2deg or back using deg2rad.

angle(z) |> rad2deg
> 53.13010235415598

We can perform all the normal arithmetic operations with complex numbers.

z1 = 2+3im;
z2 = -3-2im;

@show z1 + z2
> z1 + z2 = -1 + 1im

@show z1 - z2
> z1 - z2 = 5 + 5im

@show 2*z1
> 2z1 = 4 + 6im

@show z1 * z2
> z1 * z2 = 0 - 13im

@show z1 / z2
> z1 / z2 = -0.9230769230769231 - 0.38461538461538464im

@show z1^2
> z1 ^ 2 = -5 + 12im

We can perform all of the normal trig and exponential functions with complex numbers too.

@show sin(z)
> sin(z) = 3.853738037919377 - 27.016813258003932im

@show cos(z)
> cos(z) = -27.034945603074224 - 3.851153334811777im

@show tan(z)
> tan(z) = -0.0001873462046294785 + 0.9993559873814731im

@show exp(z)
> exp(z) = -13.128783081462158 - 15.200784463067954im

@show log(z)
> log(z) = 1.6094379124341003 + 0.9272952180016122im