Go 中复数的 "real" 和 "imaginary" 部分有什么区别?
What's the difference between "real" and "imaginary" parts of a complex numer in Go?
当我遇到一些奇怪的事情时,我正在阅读 Go 的 complex128 and complex64 数据类型的文档:
"complex128 is the set of all complex numbers with float64 real and imaginary parts."
并且:
"complex64 is the set of all complex numbers with float32 real and imaginary parts."
更具体地说:
"real and imaginary parts."
这是什么意思?一个数字怎么可能是 "real" 或 "imaginary"?
老实说,这个问题不是专门针对 GoLang 的。
复数是一个数学概念。
这是一个例子:
import (
"fmt"
"math/cmplx"
)
func main() {
fmt.Println(cmplx.Sqrt(-1))
}
预期输出:
(0+1i)
有一个名为 "cmplx" 的包可以处理复数。所以 cmplx 的 Sqrt 类似于数学一,但它 returns 是一个复数。
如你所见,输出由0
和1i
组成,最后一个是虚部,因为我们无法得到"-1"
的平方根。
对于复数,请参阅 Wikipedia。
Go 唯一特定的主题是 "complex" 类型是 Go 中内置的,因此与其他语言不同,您可以在不导入额外包的情况下对它们执行基本操作:
package main
import (
"fmt"
)
func main() {
c1 := 1i
c2 := 2 + 3i
fmt.Println(c1 * c1) // i^2 = -1
fmt.Println(c1 + c2) // i + (2+3i) = 2+4i
}
对于更高级的操作,您可以使用 math/cmplx
包,类似于实数的 math
包(作为习惯的答案)。
当我遇到一些奇怪的事情时,我正在阅读 Go 的 complex128 and complex64 数据类型的文档:
"complex128 is the set of all complex numbers with float64 real and imaginary parts."
并且:
"complex64 is the set of all complex numbers with float32 real and imaginary parts."
更具体地说:
"real and imaginary parts."
这是什么意思?一个数字怎么可能是 "real" 或 "imaginary"?
老实说,这个问题不是专门针对 GoLang 的。
复数是一个数学概念。
这是一个例子:
import (
"fmt"
"math/cmplx"
)
func main() {
fmt.Println(cmplx.Sqrt(-1))
}
预期输出:
(0+1i)
有一个名为 "cmplx" 的包可以处理复数。所以 cmplx 的 Sqrt 类似于数学一,但它 returns 是一个复数。
如你所见,输出由0
和1i
组成,最后一个是虚部,因为我们无法得到"-1"
的平方根。
对于复数,请参阅 Wikipedia。
Go 唯一特定的主题是 "complex" 类型是 Go 中内置的,因此与其他语言不同,您可以在不导入额外包的情况下对它们执行基本操作:
package main
import (
"fmt"
)
func main() {
c1 := 1i
c2 := 2 + 3i
fmt.Println(c1 * c1) // i^2 = -1
fmt.Println(c1 + c2) // i + (2+3i) = 2+4i
}
对于更高级的操作,您可以使用 math/cmplx
包,类似于实数的 math
包(作为习惯的答案)。