In this tutorial, we will learn about the complex128 data type in Go. We will cover the basics of defining and using complex numbers, including how to perform arithmetic operations and access the real and imaginary parts.
The complex128
data type in Go is used to represent complex numbers, which have both real and imaginary parts. Each part is a float64 value.
Complex numbers can be defined using the complex
function or by directly assigning values to the real and imaginary parts.
var c1 complex128 = complex(3, 4)
c2 := 2 + 3i
The real and imaginary parts of a complex number can be accessed using the real
and imag
functions, respectively.
r := real(c1)
i := imag(c1)
Arithmetic operations such as addition, subtraction, multiplication, and division can be performed on complex numbers.
sum := c1 + c2
difference := c1 - c2
product := c1 * c2
quotient := c1 / c2
We can define and use complex numbers in Go to represent values with real and imaginary parts.
For example,
c1
using the complex
function.c2
using a direct assignment.package main
import "fmt"
func main() {
var c1 complex128 = complex(3, 4)
c2 := 2 + 3i
fmt.Println(c1)
fmt.Println(c2)
}
(3+4i) (2+3i)
We can access the real and imaginary parts of a complex number in Go using the real and imag functions.
For example,
c
.real
and imag
functions to extract the real and imaginary parts.package main
import "fmt"
func main() {
c := 3 + 4i
r := real(c)
i := imag(c)
fmt.Printf("Real part: %f, Imaginary part: %f\n", r, i)
}
Real part: 3.000000, Imaginary part: 4.000000
We can perform arithmetic operations on complex numbers in Go.
For example,
c1
and c2
.package main
import "fmt"
func main() {
c1 := 3 + 4i
c2 := 1 + 2i
sum := c1 + c2
difference := c1 - c2
product := c1 * c2
quotient := c1 / c2
fmt.Println("Sum:", sum)
fmt.Println("Difference:", difference)
fmt.Println("Product:", product)
fmt.Println("Quotient:", quotient)
}
Sum: (4+6i) Difference: (2+2i) Product: (-5+10i) Quotient: (2.2-0.4i)
We can pass complex numbers to functions and return complex numbers from functions in Go.
For example,
conjugate
that takes a complex number and returns its conjugate.package main
import "fmt"
func conjugate(c complex128) complex128 {
return complex(real(c), -imag(c))
}
func main() {
c := 3 + 4i
fmt.Println("Original:", c)
fmt.Println("Conjugate:", conjugate(c))
}
Original: (3+4i) Conjugate: (3-4i)