Golang complex() Function with Examples

Golang | complex() Function: Here, we are going to learn about the built-in complex() function with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 14, 2021 [Last updated : March 15, 2023]

complex() Function

In the Go programming language, the complex() is a built-in function that is used to construct a complex value from two floating-point values. The real and imaginary parts of the complex value must be of the same size (either float32 or float64), and the return value will be the corresponding complex type.

It accepts two parameters (r, i FloatType), where r is the real part and i is the imaginary part of the complex number and returns the complex type (complex number).

Syntax

func complex(r, i FloatType) ComplexType

Parameter(s)

  • r, i : The values of real and imaginary parts to construct a complex type number.

Return Value

The return type of the complex() function is ComplexType and returns the complex type (complex number).

Example 1

// Golang program to demonstrate the
// example of complex() function

package main

import (
	"fmt"
)

func main() {
	// Constructing complex values
	c1 := complex(1.2345, 54321.0)
	c2 := complex(10, 20)
	c3 := complex(-10.5, 20.5)
	c4 := complex(10.12, -20.5)
	c5 := complex(-10.45, -20.5)

	// Printing the types and values
	fmt.Printf("c1: %T, %v\n", c1, c1)
	fmt.Printf("c2: %T, %v\n", c2, c2)
	fmt.Printf("c3: %T, %v\n", c3, c3)
	fmt.Printf("c4: %T, %v\n", c4, c4)
	fmt.Printf("c5: %T, %v\n", c5, c5)
}

Output

c1: complex128, (1.2345+54321i)
c2: complex128, (10+20i)
c3: complex128, (-10.5+20.5i)
c4: complex128, (10.12-20.5i)
c5: complex128, (-10.45-20.5i)

Example 2

// Golang program to demonstrate the
// example of complex() function

package main

import (
	"fmt"
)

func main() {
	// Declaring & assigning float32, float64
	var a, b float32
	var c, d float64

	a = 10.56
	b = 25.50
	c = 1234.5678
	d = -165727.29982

	// Constructing complex values
	c1 := complex(a, b)
	c2 := complex(c, d)

	// Printing the types and values
	fmt.Printf("a : %T, %v\n", a, a)
	fmt.Printf("b : %T, %v\n", b, b)
	fmt.Printf("c1: %T, %v\n", c1, c1)
	fmt.Println()

	fmt.Printf("c : %T, %v\n", c, c)
	fmt.Printf("d : %T, %v\n", d, d)
	fmt.Printf("c2: %T, %v\n", c2, c2)
}

Output

a : float32, 10.56
b : float32, 25.5
c1: complex64, (10.56+25.5i)

c : float64, 1234.5678
d : float64, -165727.29982
c2: complex128, (1234.5678-165727.29982i)

Golang builtin Package »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.