The type complex128
in Golang is the set of all complex numbers with float64
real and imaginary parts.
Complex numbers consist of a real and an imaginary part, as illustrated below:
To create a complex128
number in Golang, you can use the in-built complex
function. The prototype of the complex
function is shown below:
func complex(real, imaginary FloatType) ComplexType
If you provide the complex
function with arguments of type float64
, it returns a type complex128
value.
An alternative method of creating a complex number is as follows:
temp := 1 + 4i
The declaration shown above creates a complex number, with as the real part and as the imaginary part.
The complex128
type supports the usual complex number operations, e.g., addition, subtraction, multiplication, division, etc.
The code below shows how the complex128
type works in Golang:
package mainimport ("fmt")func main() {// initializing real and imaginary partsvar real float64 = 5var img float64 = 10// intiializing complex numberscomplex1 := complex(real, img)complex2 := 2 + 4i// performing arithmetic operationsfmt.Println("Addition: ", complex1, " + ", complex2, " = ", complex1 + complex2)fmt.Println("Subtraction: ", complex1, " - ", complex2, " = ", complex1 - complex2)fmt.Println("Multiplication: ", complex1, " * ", complex2, " = ", complex1 * complex2)fmt.Println("Division: ", complex1, " / ", complex2, " = ", complex1 / complex2)}
First, the code initializes two complex128
values: complex1
and complex2
. complex1
is initialized using the in-built complex
function by providing it with two float64
values. complex2
is initialized using the Golang shorthand assignment operator.
Lines perform the arithmetic operations on the complex128
values and output the results accordingly. These arithmetic operations follow the mathematical rules defined for complex numbers.
Free Resources