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

Ora*_*bîg 1 type-conversion go 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))
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

main.go:11: cannot convert x (type float64) to type complex128
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的方法,但无法找到如何转换float64complex128(只是为了能够cmplx.Sqrt()在负数上使用函数).

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

icz*_*cza 8

你真的不想转换为float64,complex128而是想要构造一个complex128指定实部的值.

为此可以使用内置complex()函数:

func complex(r, i FloatType) ComplexType
Run Code Online (Sandbox Code Playgroud)

使用它你的sqrt()功能:

func sqrt(x float64) string {
    if x < 0 {
        return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
    }
    return fmt.Sprint(math.Sqrt(x))
}
Run Code Online (Sandbox Code Playgroud)

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))
}
Run Code Online (Sandbox Code Playgroud)