使用非常简单的代码:
package main
import (
"fmt"
"math"
"math/cmplx"
)
func sqrt(x float64) string {
if x < 0 {
return fmt.Sprint(cmplx.Sqrt(complex128(x)))
}
return fmt.Sprint(math.Sqrt(x))
}
func main() {
fmt.Println(sqrt(2), sqrt(-4))
}
我收到以下错误消息:
main.go:11: cannot convert x (type float64) to type complex128
我尝试了不同的方法,但无法找到如何将float64
转换为complex128
(只是为了能够在负数上使用cmplx.Sqrt()
函数)。
处理此问题的正确方法是什么?
答案 0 :(得分:8)
您并非真的想要将float64
转换为complex128
,而是希望构建一个complex128
值,您可以在其中指定实际部分。
为此可以使用内置complex()
函数:
func complex(r, i FloatType) ComplexType
使用sqrt()
功能:
func sqrt(x float64) string {
if x < 0 {
return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
}
return fmt.Sprint(math.Sqrt(x))
}
在Go Playground上尝试。
注意:强>
您可以在不使用复数的情况下计算负float
数的平方根:它将是一个复数值,其实部为0
,虚部为math.Sqrt(-x)i
(所以结果:(0+math.Sqrt(-x)i)
):
func sqrt2(x float64) string {
if x < 0 {
return fmt.Sprintf("(0+%.15fi)", math.Sqrt(-x))
}
return fmt.Sprint(math.Sqrt(x))
}