英文:
How to convert float to complex?
问题
使用complex()函数可以将float64类型转换为complex128类型。在这种情况下,你可以将x作为实部,0作为虚部传递给complex()函数。以下是修改后的代码:
package main
import (
	"fmt"
	"math"
	"math/cmplx"
)
func sqrt(x float64) string {
	if x < 0 {
		return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
	}
	return fmt.Sprint(math.Sqrt(x))
}
func main() {
	fmt.Println(sqrt(2), sqrt(-4))
}
这样修改后的代码将能够正确处理将float64转换为complex128的情况。
英文:
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))
}
I get the following error message :
main.go:11: cannot convert x (type float64) to type complex128
I tried different ways, but couldn't find out how to convert a float64 to complex128 (just to be able to use cmplx.Sqrt() function on a negative number).
Which is the correct way to handle this ?
答案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上尝试一下。
注意:
你可以计算负数的平方根而不使用复数:结果将是一个实部为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))
}
英文:
You don't really want to convert a float64 to complex128 but rather you want to construct a complex128 value where you specify the real part.
For that can use the builtin complex() function:
func complex(r, i FloatType) ComplexType
Using it your sqrt() function:
func sqrt(x float64) string {
	if x < 0 {
		return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
	}
	return fmt.Sprint(math.Sqrt(x))
}
Try it on the Go Playground.
Note:
You can calculate the square root of a negative float number without using complex numbers: it will be a complex value whose real part is 0 and imaginary part is math.Sqrt(-x)i (so the result: (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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论