Golang 第三章 3.复数

  • By v2ray节点

  • 2026-03-16 14:35:33

  • 评论

Go 提供了 内置的复数类型

复数由 实部 + 虚部 组成:

a+bi

其中:

  • a → 实部
  • b → 虚部
  • i → 虚数单位(√-1)


Go 中的复数类型

Go 提供两种复数类型:

complex64
complex128

区别:


类型实部虚部
complex64float32float32
complex128float64float64

例如:

var x complex128
var y complex64


复数常量

Go 可以直接写复数:

z := 3 + 4i

这里:

实部 = 3
虚部 = 4

Go 会自动推断类型:

complex128


complex 函数

Go 提供 complex() 函数创建复数:

z := complex(3, 4)

表示:

3 + 4i


获取实部和虚部

Go 提供两个内置函数:

real(z)imag(z)

示例:

z := 3 + 4ifmt.Println(real(z)) // 3fmt.Println(imag(z)) // 4


复数运算

复数支持所有基本运算:

x := 1 + 2i
y := 3 + 4i
fmt.Println(x + y)
fmt.Println(x - y)
fmt.Println(x * y)
fmt.Println(x / y)

输出示例:

(4+6i)
(-2-2i)
(-5+10i)
(0.44+0.08i)


数学库支持

Go 的数学包:

import "math/cmplx"

提供复数运算函数:

例如:


函数作用
cmplx.Abs(z)复数模
cmplx.Sqrt(z)开平方
cmplx.Exp(z)e^z
cmplx.Log(z)ln(z)
cmplx.Pow(x,y)x^y

示例:

z := 1 + 2i
fmt.Println(cmplx.Abs(z))
fmt.Println(cmplx.Sqrt(z))


复数示例程序

package main
import (
    "fmt"
    "math/cmplx"
)
func main() {
    z := 1 + 2i
    fmt.Println("z =", z)
    fmt.Println("real =", real(z))
    fmt.Println("imag =", imag(z))
    fmt.Println("abs =", cmplx.Abs(z))
}

输出:

z = (1+2i)
real = 1
imag = 2
abs = 2.23606797749979


复数常量

Go 支持 复数常量表达式

const z = 2 + 3i

也可以:

const i = 1i


总结

Go 复数的核心点:


功能用法
类型complex64 / complex128
创建3+4icomplex(3,4)
实部real(z)
虚部imag(z)
数学函数math/cmplx


v2ray节点购买