The complex
function in Golang is a built-in function that constructs a complex value from two floating-point values.
The floating-point values represent the real and imaginary parts of the complex value. To use the complex
function, you must ensure that both floating-point values are of the same size, i.e., they are both either float32
objects or float64
objects.
The process is illustrated below:
The prototype of the complex
function is shown below:
func complex(r, i FloatType) ComplexType
The complex
function takes the following two FloatType
objects as parameters:
r
: The real part of the complex value.i
: The imaginary part of the complex value.The complex
function returns a ComplexType
object that represents a complex value constructed from the provided parameters for the real and imaginary values.
If the parameters r
and i
are float32
objects, then the complex
function returns a complex64
object; otherwise, if r
and i
are float64
objects, then the complex
function returns a complex128
object.
The code below shows how the complex
function works in Golang:
package mainimport ("fmt")func main() {// initializing complex valuesa := complex(5, 2)b := complex (10, 4)// printing complex valuesfmt.Println("The complex value a is:", a)fmt.Println("The complex value b is:", b)// printing real and imaginary partsfmt.Println("The real part of a is", real(a), "and the imaginary part is", imag(a))fmt.Println("The real part of b is", real(b), "and the imaginary part is", imag(b))}
The complex
function in lines and initializes a complex object based on the values provided for the real and imaginary parts. The code then outputs the complex values constructed by the complex
function in lines and .
The real
and imag
functions in lines and extract the real and imaginary parts of a complex value, respectively.
Free Resources