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

3

With the very simple code :

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个回答

11
您不是真的想将 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))
}

谢谢,你说得对,那就是我在寻找的东西。 - Orabîg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接