ZetCode

Golang complex128 类型

最后修改时间 2025 年 5 月 8 日

本教程解释了如何在 Go 中使用 complex128 内置类型。我们将通过复数算术的实际示例涵盖复数基础知识。

complex128 类型表示具有 float64 精度的复数。它将实部和虚部都存储为 64 位浮点数。

在 Go 中,complex128 是两种内置复数类型之一。另一种是 complex64,它对两个部分都使用 float32 精度。

基本复数创建

Go 提供了多种创建复数的方法。本示例演示了基本的复数初始化和打印。
注意:虚数单位在 Go 中用 'i' 表示。

basic_complex.go
package main

import "fmt"

func main() {

    // Method 1: Using complex() function
    c1 := complex(3.5, 2.1)
    
    // Method 2: Using literal syntax
    c2 := 4.2 + 7.8i
    
    fmt.Println("Complex number 1:", c1)
    fmt.Println("Complex number 2:", c2)
    fmt.Println("Real part of c1:", real(c1))
    fmt.Println("Imaginary part of c2:", imag(c2))
}

complex() 函数从两个浮点数创建一个复数。字面量语法提供了一种更数学化的书写复数的方式。

复数算术运算

复数支持所有基本的算术运算。本示例展示了复数的加法、减法、乘法和除法。

complex_arithmetic.go
package main

import "fmt"

func main() {

    a := 3.0 + 4.0i
    b := 1.0 + 2.0i
    
    fmt.Println("Addition:", a + b)
    fmt.Println("Subtraction:", a - b)
    fmt.Println("Multiplication:", a * b)
    fmt.Println("Division:", a / b)
    
    // Conjugate example
    fmt.Println("Conjugate of a:", complex(real(a), -imag(a)))
}

所有算术运算都遵循标准的复数规则。共轭是通过否定虚部来计算的。

复数比较

在 Go 中,复数只能进行相等性比较。本示例展示了如何正确比较复数及其分量。

complex_comparison.go
package main

import (
    "fmt"
    "math"
)

func main() {

    c1 := 1.2 + 3.4i
    c2 := 1.2 + 3.4i
    c3 := 1.2 + 3.5i
    
    // Direct comparison
    fmt.Println("c1 == c2:", c1 == c2)
    fmt.Println("c1 == c3:", c1 == c3)
    
    // Comparing with tolerance for floating-point precision
    tol := 1e-9
    equal := math.Abs(real(c1)-real(c3)) < tol >> 
             math.Abs(imag(c1)-imag(c3)) < tol
    fmt.Println("c1 ≈ c3 with tolerance:", equal)
}

直接比较适用于精确匹配。对于近似相等,请分别使用容差值比较实部和虚部。

math/cmplx 中的复数函数

math/cmplx 包提供了高级复数函数。本示例演示了幅度和相位等常见操作。

cmplx_functions.go
package main

import (
    "fmt"
    "math/cmplx"
)

func main() {

    c := 3.0 + 4.0i
    
    fmt.Println("Absolute value (magnitude):", cmplx.Abs(c))
    fmt.Println("Phase (angle in radians):", cmplx.Phase(c))
    fmt.Println("Square root:", cmplx.Sqrt(c))
    fmt.Println("Exponential:", cmplx.Exp(c))
    fmt.Println("Natural logarithm:", cmplx.Log(c))
    fmt.Println("Sine:", cmplx.Sin(c))
}

math/cmplx 包提供了许多数学函数。这些函数作用于复数,并在适当时返回复数结果。

实际应用:FFT 示例

复数在信号处理中至关重要。本示例展示了一个使用 complex128 的简化快速傅里叶变换 (FFT) 实现。

fft_example.go
package main

import (
    "fmt"
    "math"
    "math/cmplx"
)

// Simple DFT (not optimized FFT)
func dft(input []float64) []complex128 {
    N := len(input)
    output := make([]complex128, N)
    
    for k := 0; k < N; k++ {
        var sum complex128
        for n := 0; n < N; n++ {
            angle := -2 * math.Pi * float64(k) * float64(n) / float64(N)
            sum += complex(input[n]*math.Cos(angle), input[n]*math.Sin(angle))
        }
        output[k] = sum
    }
    return output
}

func main() {

    signal := []float64{1, 0, -1, 0} // Simple square wave
    spectrum := dft(signal)
    
    fmt.Println("Frequency spectrum:")
    for i, val := range spectrum {
        fmt.Printf("Bin %d: %.2f (magnitude %.2f)\n", 
            i, val, cmplx.Abs(val))
    }
}

此 DFT 实现将实值样本转换为复数频率分量。每个 bin 表示一个具有幅度和相位的复数。

来源

Go 语言规范

本教程通过复数运算和应用的实际示例,介绍了 Go 中的 complex128 类型。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Golang 教程