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

How to convert float to complex?

使用非常简单的代码:

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

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

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