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.
z := complex(3, 4) // complex128 fmt.Println(real(z), imag(z)) // 3 4
Try it
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.
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
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.5iand0x10iare untyped imaginary constants, so1 + 2iis a complex constant. - Zero value is
(0+0i). - Printing:
fmtshows(3+4i). Verbs like%.2fapply to both parts. - Math functions for complex values live in the
math/cmplxpackage: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.
Related
float32andfloat64,len(),+ - * / %,math- Lessons: Numbers, Basic types