Golang imag 函数
最后修改时间 2025 年 5 月 8 日
本教程将讲解如何在 Go 中使用 `imag` 内置函数。我们将通过实际示例讲解复数基础知识以及虚部提取。
`imag` 函数用于提取 Go 中复数的虚部。它同时支持 `complex64` 和 `complex128` 类型。该函数返回一个浮点数值。
在 Go 中,`imag` 是用于复数的两个内置函数之一。另一个是 `real`。两者共同提供了访问复数组成部分的功能。
基本的 imag 函数示例
`imag` 最简单的用法是从复数中提取虚部。本示例展示了基本的虚部提取。
注意: 结果类型与复数的组件类型匹配。
basic_imag.go
package main
import "fmt"
func main() {
c1 := complex(3, 4) // 3 + 4i
c2 := complex(1.5, -2.5) // 1.5 - 2.5i
fmt.Println("Imaginary part of c1:", imag(c1))
fmt.Println("Imaginary part of c2:", imag(c2))
// Type demonstration
fmt.Printf("Type of imag(c1): %T\n", imag(c1))
fmt.Printf("Type of imag(c2): %T\n", imag(c2))
}
该程序创建了两个复数并提取了它们的虚部。输出显示了浮点数值及其类型。
将 imag 与 complex64 一起使用
`imag` 函数同时支持 `complex64` 和 `complex128` 类型。本示例展示了与较小的 `complex64` 类型一起使用的用法。
complex64_imag.go
package main
import "fmt"
func main() {
var c1 complex64 = complex(1.2, 3.4)
var c2 complex64 = complex(-5.6, 7.8)
im1 := imag(c1)
im2 := imag(c2)
fmt.Println("Imaginary parts:", im1, im2)
fmt.Printf("Types: %T, %T\n", im1, im2)
sum := im1 + im2
fmt.Println("Sum of imaginary parts:", sum)
}
该示例表明 `imag` 对 `complex64` 返回 `float32`。我们可以对提取的虚部进行算术运算。
计算中的虚部
提取的虚部可用于数学计算。本示例展示了 `imag` 在计算中的实际用法。
calculation_imag.go
package main
import (
"fmt"
"math"
)
func main() {
c := complex(3.0, 4.0) // 3 + 4i
// Calculate magnitude using real and imag parts
magnitude := math.Sqrt(math.Pow(real(c), 2) + math.Pow(imag(c), 2))
// Calculate phase angle (in radians)
phase := math.Atan2(imag(c), real(c))
fmt.Printf("Complex number: %v\n", c)
fmt.Printf("Magnitude: %.2f\n", magnitude)
fmt.Printf("Phase angle: %.2f radians\n", phase)
}
该程序计算复数的幅值和相位角。它在计算中同时使用了 `real` 和 `imag` 函数。
函数返回值中的虚部
`imag` 函数可以直接在 return 语句中使用。本示例展示了一个返回复数虚部的函数。
function_imag.go
package main
import "fmt"
func getImaginaryPart(c complex128) float64 {
return imag(c)
}
func main() {
numbers := []complex128{
complex(1, 2),
complex(0, -3),
complex(4.5, 6.7),
}
for _, num := range numbers {
im := getImaginaryPart(num)
fmt.Printf("Number: %v, Imaginary part: %.1f\n", num, im)
}
}
`getImaginaryPart` 函数封装了 `imag` 调用。这使得代码更具可读性,并且可重用于复数运算。
比较虚部
提取的虚部可以像常规浮点数一样进行比较。本示例演示了对虚部进行比较运算。
compare_imag.go
package main
import (
"fmt"
"math"
)
func main() {
c1 := complex(3, 4)
c2 := complex(1, 5)
c3 := complex(0, -4)
// Compare imaginary parts
fmt.Println("c1 imaginary > c2 imaginary:", imag(c1) > imag(c2))
fmt.Println("c2 imaginary == 5:", imag(c2) == 5)
fmt.Println("c3 imaginary is negative:", imag(c3) < 0)
// Floating-point comparison with tolerance
c4 := complex(2, math.Pi)
fmt.Println("c4 imaginary ≈ π:", math.Abs(imag(c4)-math.Pi) < 0.0001)
}
该示例展示了对虚部的各种比较运算。它包括精确比较和带容差的浮点数比较。
来源
本教程通过复数操作和虚部提取的实际示例,讲解了 Go 中的 `imag` 函数。