Finding the Square Root of the Complex Number in Golang

Here, we are going to learn how to find the square root of the complex number in Golang?
Submitted by IncludeHelp, on August 11, 2021 [Last updated : March 05, 2023]

How to find the square root of the complex number in Golang?

Go language has a huge library with various constants and functions for any type of data that provides inbuilt support for the basic constants and mathematical constants for complex numbers also. To work with complex numbers, the Go language has complex data types (complex64, complex128) and "math/cmplx" package. The "math/cmplx" package has various functions for different tasks.

To find the square root of the complex number – we use Sqrt() function of cmplx package.

Syntax

func Sqrt(x complex128) complex128

The function accepts a complex number as a parameter and returns the square root of the same type.

Consider the below examples explaining – how to find the square root of the complex numbers in Golang?

Golang code to find the square root of the complex number

Example 1

// Golang program to demonstrate how to find
// the square root of the given complex number

package main

import (
	"fmt"
	"math/cmplx"
)

// Main function
func main() {
	fmt.Printf("cmplx.Sqrt(10 - 15i): %.2f\n", cmplx.Sqrt(10-15i))
	fmt.Printf("cmplx.Sqrt(-3 - 9i) : %.2f\n", cmplx.Sqrt(-3-9i))
	fmt.Printf("cmplx.Sqrt(9 - 16i) : %.2f\n", cmplx.Sqrt(9-16i))
}

Output

cmplx.Sqrt(10 - 15i): (3.74-2.00i)
cmplx.Sqrt(-3 - 9i) : (1.80-2.50i)
cmplx.Sqrt(9 - 16i) : (3.70-2.16i)

Example 2

// Golang program to demonstrate how to find
// the square root of the given complex number

package main

import (
	"fmt"
	"math/cmplx"
)

// Main function
func main() {
	// Creating complex numbers
	x := complex(0, 2)
	y := complex(4, 6)

	// Finding the square roots
	sqrt_x := cmplx.Sqrt(x)
	sqrt_y := cmplx.Sqrt(y)

	// Displaying complex numbers and square roots
	fmt.Println("x: ", x)
	fmt.Println("y: ", y)
	
	fmt.Println("Square root of", x, "is", sqrt_x)
	fmt.Println("Square root of", y, "is", sqrt_y)
}

Output

x:  (0+2i)
y:  (4+6i)
Square root of (0+2i) is (1+1i)
Square root of (4+6i) is (2.3676045437243083+1.2671034983236331i)




Comments and Discussions!

Load comments ↻





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