Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Built-in Functions

Go complex(), real() and imag() functions

Reference for Go complex numbers: build them with complex(), split them with real() and imag(), the complex64 and complex128 types, and math/cmplx.

Go has complex numbers as a built-in type. complex(r, i) builds a value from a real part and an imaginary part, and real(z) and imag(z) take it apart again. The two types are complex64 (two float32 parts) and complex128 (two float64 parts, the default).

Arithmetic with + - * / and comparison with == and != work directly on complex values. Ordering (<) does not, because complex numbers have no natural order.

Go
z := complex(3, 4) // complex128
fmt.Println(real(z), imag(z)) // 3 4

Try it

Go Build, split and calculate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go complex64 and square roots of negatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func complex(r, i FloatType) ComplexType
func real(c ComplexType) FloatType
func imag(c ComplexType) FloatType
Name Description
r, i Real and imaginary parts. Both must have the same float type (float32 or float64) or be untyped constants.
c A complex value.

Returns: complex(float32, float32) is a complex64; complex(float64, float64) is a complex128. real and imag return float32 for a complex64 and float64 for a complex128.

Edge cases: if both arguments are untyped constants, the result is an untyped complex constant that becomes complex128 unless the context says otherwise. Mixing a float32 with a float64 argument is a compile error.

Usage notes

  • Imaginary literals: 2i, 1.5i and 0x10i are untyped imaginary constants, so 1 + 2i is a complex constant.
  • Zero value is (0+0i).
  • Printing: fmt shows (3+4i). Verbs like %.2f apply to both parts.
  • Math functions for complex values live in the math/cmplx package: Abs, Phase, Sqrt, Exp, Pow, Conj, Polar, Rect.
  • Division by zero with complex floating-point values does not panic; it yields infinities or NaN parts, as with floats.
  • Equality compares both parts exactly, so floating-point rounding matters. Compare cmplx.Abs(a-b) with a tolerance instead.
  • Complex numbers are rarely used outside numeric code (signal processing, fractals), but they are a real built-in, not a library type.