What is the complex function in Golang?

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

Parameters

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.

Return 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.

Example

The code below shows how the complex function works in Golang:

package main
import (
"fmt"
)
func main() {
// initializing complex values
a := complex(5, 2)
b := complex (10, 4)
// printing complex values
fmt.Println("The complex value a is:", a)
fmt.Println("The complex value b is:", b)
// printing real and imaginary parts
fmt.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))
}

Explanation

The complex function in lines 1010 and 1111 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 1414 and 1515.

The real and imag functions in lines 1818 and 1919 extract the real and imaginary parts of a complex value, respectively.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved