Golang ComplexType
最后修改时间 2025 年 5 月 8 日
本教程将讲解如何在 Go 中使用 ComplexType 内置类型。我们将通过复数运算的实际示例来介绍复数基础知识。
Go 中的 ComplexType 表示具有浮点数分量的复数。Go 提供了两种复数类型:complex64 和 complex128。它们分别对应 32 位和 64 位浮点数分量。
复数在科学计算、信号处理和图形学中非常有用。Go 提供了用于创建和操作复数的内置函数。如果需要,还可以单独访问实部和虚部。
基本复数创建
创建复数的最简单方法是使用 complex 函数。此示例演示了基本的复数创建和分量访问。
注意: 复数文字使用 (a+bi) 格式。
package main
import "fmt"
func main() {
// Create complex numbers
a := complex(2, 3) // 2 + 3i
b := 4 + 5i // Literal syntax
// Access components
realA := real(a)
imagA := imag(a)
fmt.Println("a =", a)
fmt.Println("b =", b)
fmt.Printf("Real part of a: %.1f\n", realA)
fmt.Printf("Imaginary part of a: %.1f\n", imagA)
}
complex 函数根据两个浮点数创建复数。可以使用 real 和 imag 访问实部和虚部。复数文字提供了方便的初始化语法。
复数算术运算
复数支持标准的算术运算,如加法和乘法。此示例展示了复数的基本算术运算。
package main
import "fmt"
func main() {
a := 3 + 4i
b := 1 + 2i
// Arithmetic operations
sum := a + b
difference := a - b
product := a * b
quotient := a / b
fmt.Println("a + b =", sum)
fmt.Println("a - b =", difference)
fmt.Println("a * b =", product)
fmt.Println("a / b =", quotient)
}
复数运算遵循复数的标准数学规则。乘法和除法使用公式 (a+bi)(c+di) = (ac-bd)+(ad+bc)i。如果混合类型,结果会自动提升到较大的类型。
复数比较
复数可以进行相等性比较,但不能进行顺序比较。此示例演示了复数的比较运算。
package main
import "fmt"
func main() {
a := 3.0 + 4i
b := 3.0 + 4i
c := 3.1 + 4i
// Equality comparison
fmt.Println("a == b:", a == b)
fmt.Println("a == c:", a == c)
// Note: No ordering operators (<, >, etc.)
// fmt.Println("a < c:", a < c) // Compile error
}
当实部和虚部都相等时,复数才相等。Go 不支持复数的顺序运算符(<, >)。这符合复数比较的数学惯例。
复数数学函数
math/cmplx 包提供了高级复数函数。此示例演示了常见的复数数学运算。
package main
import (
"fmt"
"math/cmplx"
)
func main() {
z := 3 + 4i
// Complex math operations
conjugate := cmplx.Conj(z)
absolute := cmplx.Abs(z)
phase := cmplx.Phase(z)
sqrt := cmplx.Sqrt(z)
fmt.Println("z =", z)
fmt.Println("Conjugate:", conjugate)
fmt.Printf("Absolute value: %.2f\n", absolute)
fmt.Printf("Phase angle: %.2f radians\n", phase)
fmt.Println("Square root:", sqrt)
}
math/cmplx 包提供了 Conj、Abs 和 Sqrt 等函数。这些函数实现了标准的数学复数运算。该包还包括三角函数、指数函数和对数函数。
复数的实际应用
复数对于求解二次方程很有用。此示例演示了使用复数来求解方程的根。
package main
import (
"fmt"
"math/cmplx"
)
func quadraticRoots(a, b, c float64) (complex128, complex128) {
discriminant := b*b - 4*a*c
sqrtDiscriminant := cmplx.Sqrt(complex(discriminant, 0))
root1 := (-complex(b, 0) + sqrtDiscriminant) / complex(2*a, 0)
root2 := (-complex(b, 0) - sqrtDiscriminant) / complex(2*a, 0)
return root1, root2
}
func main() {
// Real roots
r1, r2 := quadraticRoots(1, -3, 2)
fmt.Println("Roots of x² - 3x + 2 = 0:")
fmt.Println("Root 1:", r1)
fmt.Println("Root 2:", r2)
// Complex roots
r1, r2 = quadraticRoots(1, 0, 1)
fmt.Println("\nRoots of x² + 1 = 0:")
fmt.Println("Root 1:", r1)
fmt.Println("Root 2:", r2)
}
复数可以求解判别式为负的二次方程。同一个函数可同时处理实数根和复数根。这展示了复数在计算中的实际价值。
来源
本教程通过复数创建、运算和应用的实际示例,讲解了 Go 中的 ComplexType。