Open In App

Finding the Square Root of the Complex Number in Golang

Improve
Improve
Like Article
Like
Save
Share
Report

Go language provides inbuilt support for basic constants and mathematical functions for complex numbers with the help of the cmplx package. You are allowed to find the square root of the specified complex number with the help of Sqrt() function provided by the math/cmplx package. In this function, q is chosen so that real(q) >= 0 and imag(q) has the same sign as imag(y). So, to access the Sqrt() function you need to add a math/cmplx package in your program with the help of the import keyword.

Syntax:

func Sqrt(y complex128) complex128

Let us discuss this concept with the help of the given examples:

Example 1:




// Golang program to illustrate how to find
// the square root of the given complex number
  
package main
  
import (
    "fmt"
    "math/cmplx"
)
  
// Main function
func main() {
  
    // Finding the square root of 
    // the specified complex number
    // Using Sqrt() function
    res_1 := cmplx.Sqrt(8 - 6i)
    res_2 := cmplx.Sqrt(-4 + 12i)
    res_3 := cmplx.Sqrt(-3 - 9i)
  
    // Displaying the result
    fmt.Printf("Result 1: %.2f", res_1)
    fmt.Printf("\nResult 2:  %.2f", res_2)
    fmt.Printf("\nResult 3:  %.2f", res_3)
}


Output:

Result 1: (3.00-1.00i)
Result 2:  (2.08+2.89i)
Result 3:  (1.80-2.50i)

Example 2:




// Golang program to illustrate how to find
// the square root of the given complex number
  
package main
  
import (
    "fmt"
    "math/cmplx"
)
  
// Main function
func main() {
  
    cnumber_1 := complex(0, 2)
    cnumber_2 := complex(4, 6)
  
    // Finding square root
    cvalue_1 := cmplx.Sqrt(cnumber_1)
    cvalue_2 := cmplx.Sqrt(cnumber_2)
  
    // Sum of the given square roots
    res := cvalue_1 + cvalue_2
  
    // Displaying results
    fmt.Println("Complex Number 1: ", cnumber_1)
    fmt.Printf("Square Root 1: %.1f", cvalue_1)
  
    fmt.Println("\nComplex Number 2: ", cnumber_2)
    fmt.Printf("Square Root: %.1f ", cvalue_2)
    fmt.Printf("\nSum : %.1f", res)
  
}


Output:

Complex Number 1:  (0+2i)
Square Root 1: (1.0+1.0i)
Complex Number 2:  (4+6i)
Square Root: (2.4+1.3i) 
Sum : (3.4+2.3i)


Last Updated : 01 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads