如何将浮点数转换为复数?

时间:2015-06-24 09:13:34

标签: go type-conversion complex-numbers

使用非常简单的代码:

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()函数)。

处理此问题的正确方法是什么?

1 个答案:

答案 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))
}