Q:

Finding the Square Root of the Complex Number in Golang

belongs to collection: Golang Miscellaneous Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang program to demonstrate the panic() function... >>