I was reading Go's documentation for the complex128 and complex64 data types when I came across something odd:
"complex128 is the set of all complex numbers with float64 real and imaginary parts."
And:
"complex64 is the set of all complex numbers with float32 real and imaginary parts."
More specifically:
"real and imaginary parts."
What's meant by this? How can a number be "real" or "imaginary"?
The question isn't dedicated to GoLang, to be honest.
Complex numbers are a mathematical concept.
Here is an example:
import (
"fmt"
"math/cmplx"
)
func main() {
fmt.Println(cmplx.Sqrt(-1))
}
Expected output:
(0+1i)
There is a package named "cmplx" to work with complex numbers. So Sqrt of cmplx is similar to math one, but it returns a complex number instead.
As you see, and output consists of 0
and 1i
, and the last one is an imaginary part as we are not able to get a square root of "-1"
.
For complex numbers, see Wikipedia.
The only Go-specific topic is that the "complex" types are built-in in Go, so unlike in other languages you can perform basic operations on them without importing additional packages:
package main
import (
"fmt"
)
func main() {
c1 := 1i
c2 := 2 + 3i
fmt.Println(c1 * c1) // i^2 = -1
fmt.Println(c1 + c2) // i + (2+3i) = 2+4i
}
For more advanced operations, you can use the math/cmplx
package, similar to the math
package for real numbers (as in being of habits' answer).