Golang complex 函数
最后修改时间 2025 年 5 月 8 日
本教程将解释如何在 Go 中使用 `complex` 内置函数。我们将通过实际的复数运算示例来涵盖复数基础知识。
`complex` 函数从两个浮点数构建一个复数值。在 Go 中,复数是一种一流的类型,并内置支持。
Go 提供了两种复数类型:`complex64` 和 `complex128`。它们分别对应 32 位和 64 位浮点数分量。
基本复数创建
`complex` 最简单的用法是从两个浮点数创建复数。这个例子演示了基本的复数构造。
注意: 两个参数都必须是相同的浮点数类型。
basic_complex.go
package main import "fmt" func main() { // Create complex128 numbers a := complex(3.5, 2.1) b := complex(1.2, 4.7) fmt.Println("a =", a) fmt.Println("b =", b) // Perform basic arithmetic sum := a + b product := a * b fmt.Println("Sum:", sum) fmt.Println("Product:", product) }
`complex` 函数将两个浮点数合并成一个复数。Go 支持直接对复数进行算术运算。
提取实部和虚部
我们可以使用 `real` 和 `imag` 函数提取实部和虚部。此示例显示了分量提取。
components.go
package main import ( "fmt" "math" ) func main() { c := complex(4.2, 5.3) r := real(c) i := imag(c) fmt.Printf("Complex: %.2f\n", c) fmt.Printf("Real part: %.2f\n", r) fmt.Printf("Imaginary part: %.2f\n", i) // Calculate magnitude magnitude := math.Hypot(r, i) fmt.Printf("Magnitude: %.2f\n", magnitude) }
`real` 和 `imag` 函数提取分量。`math.Hypot` 计算复数的幅度。
complex64 vs complex128
Go 提供了两种具有不同精度级别的复数类型。此示例演示了它们之间的区别。
precision.go
package main import "fmt" func main() { // complex64 uses float32 components c64 := complex(float32(1.23456789), float32(9.87654321)) // complex128 uses float64 components c128 := complex(1.23456789, 9.87654321) fmt.Println("complex64:", c64) fmt.Println("complex128:", c128) // Precision difference fmt.Printf("complex64 real part: %.15f\n", real(c64)) fmt.Printf("complex128 real part: %.15f\n", real(c128)) }
`complex64` 的精度低于 `complex128`。输出显示了浮点数分量精度的差异。
复数运算
Go 支持复数的各种数学运算。此示例演示了常见的复数运算。
operations.go
package main import ( "fmt" "math/cmplx" ) func main() { a := complex(3, 4) b := complex(1, 2) // Basic arithmetic fmt.Println("a + b =", a+b) fmt.Println("a - b =", a-b) fmt.Println("a * b =", a*b) fmt.Println("a / b =", a/b) // Math functions fmt.Println("Conjugate of a:", cmplx.Conj(a)) fmt.Println("Phase (angle) of a:", cmplx.Phase(a)) fmt.Println("Square root of a:", cmplx.Sqrt(a)) }
`cmplx` 包提供了高级复数函数。基本算术运算直接与复数一起使用。
实际应用:FFT 示例
复数在信号处理中至关重要。此示例显示了一个使用复数的简单快速傅立叶变换 (FFT)。
fft_example.go
package main import ( "fmt" "math" "math/cmplx" ) func simpleFFT(input []float64) []complex128 { n := len(input) output := make([]complex128, n) for k := 0; k < n; k++ { var sum complex128 for t := 0; t < n; t++ { angle := -2 * math.Pi * float64(k) * float64(t) / float64(n) sum += complex(input[t]*math.Cos(angle), input[t]*math.Sin(angle)) } output[k] = sum } return output } func main() { signal := []float64{1, 2, 1, 2, 1, 2, 1, 2} spectrum := simpleFFT(signal) fmt.Println("Input signal:", signal) fmt.Println("FFT result:") for i, val := range spectrum { fmt.Printf("Bin %d: %.2f (magnitude %.2f)\n", i, val, cmplx.Abs(val)) } }
这个简化的 FFT 实现演示了复数的使用。结果显示了作为复数带有幅度的频率分量。
来源
本教程通过复数创建和运算的实际示例,涵盖了 Go 中的 `complex` 函数。