Finding the Square Root of the Complex Number in Golang
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:
package main
import (
"fmt"
"math/cmplx"
)
func main() {
res_1 := cmplx.Sqrt(8 - 6i)
res_2 := cmplx.Sqrt(-4 + 12i)
res_3 := cmplx.Sqrt(-3 - 9i)
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:
package main
import (
"fmt"
"math/cmplx"
)
func main() {
cnumber_1 := complex(0, 2)
cnumber_2 := complex(4, 6)
cvalue_1 := cmplx.Sqrt(cnumber_1)
cvalue_2 := cmplx.Sqrt(cnumber_2)
res := cvalue_1 + cvalue_2
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
Share your thoughts in the comments
Please Login to comment...