Golang 寻找复数平方根
Go语言通过cmplx包提供内置支持,用于基本常量和数学函数计算复数。您可以使用该包中提供的Sqrt()函数来查找指定复数的平方根,其语法为 q 会根据imag(y)的符号选择,real(q) >= 0。 因此,要访问Sqrt()函数,需要在程序中使用import关键字添加math/cmplx包。
语法:
func Sqrt(y complex128) complex128
让我们以给定的示例为例进行讨论:
示例1:
// Golang程序演示如何查找给定复数的平方根
package main
import (
"fmt"
"math/cmplx"
)
// 主函数
func main() {
// 使用Sqrt()函数寻找
// 指定复数的平方根
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)
}
输出:
Result 1: (3.00-1.00i)
Result 2: (2.08+2.89i)
Result 3: (1.80-2.50i)
示例2:
// Golang程序演示如何查找给定复数的平方根
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)
}
输出:
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)