go - 如何将 float 转换为复数?

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

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

最佳答案

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

关于go - 如何将 float 转换为复数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022456/

相关文章:

google-app-engine - go-endpoints oauth2 用户始终为零

swift - 计算解析方程中的复数

C# Complex Tanh 对于大值失败

java - 用有理指数计算复数

go - 尝试了 monad 模式,但仍然有重复的错误处理

go - 写入 channel 时从未调用 Defer

haskell - 根据输入返回字符串或 Int

java - Spring MVC "No converter found capable of converting from type java.lang.String to type org.springframework.core.io.Resource"

arrays - 如何在数组Golang中查找非重复项

c# - WPF - 将位图转换为图像源