logo

How to Use Complex Numbers in Julia 📂Julia

How to Use Complex Numbers in Julia

Overview

In Julia, complex numbers are natively supported, similar to R.

Code

Imaginary unit im

julia> z = 3 + 4im
3 + 4im

im represents the pure imaginary unit $i = \sqrt{-1}$. All the common arithmetic operations that we are familiar with can be used.

julia> typeof(z)
Complex{Int64}

julia> typeof(3.0 + 4.0im)
ComplexF64 (alias for Complex{Float64})

When checking the type, even though it’s the same complex number, the type of complex number it consists of differs. Similar to how in abstract algebra, it is distinguished whether it is an integer, in the case of $\mathbb{Z} [i]$, or a real number, in the case of $\mathbb{R} [i]$.

Real and imaginary parts real(), imag()

julia> real(z)
3

julia> imag(z)
4

Conjugate and modulus conj(), abs()

julia> conj(z)
3 - 4im

julia> abs(z)
5.0

Note that here, the modulus abs() is not specifically redefined for complex numbers but is used in its general sense of absolute value. Julia has polymorphism, which allows for this design to be naturally well-implemented.

General complex functions

julia> cos(z)
-27.034945603074224 - 3.851153334811777im

julia> log(z)
1.6094379124341003 + 0.9272952180016122im

As expected, just like with absolute values, trigonometric functions and logarithmic functions are well defined for complex numbers $\mathbb{C}$ and can be used directly in Julia without any special manipulation.

Complete Code

z = 3 + 4im
real(z)
imag(z)
conj(z)
abs(z)
cos(z)
log(z)

Environment

  • OS: Windows
  • julia: v1.7.0