Go语言的 math
模块提供了丰富的数学函数和常量,涵盖基本运算、三角函数、指数、对数、取整、特殊值等。以下是核心方法及示例说明:
1. 基本数学运算
math.Abs
取绝对值(仅 float64
)。
fmt.Println(math.Abs(-3.5)) // 输出: 3.5
fmt.Println(math.Abs(4)) // 错误!需用 math.Abs(4.0)
math.Mod
和 math.Remainder
Mod
:取余数(符号与除数相同)。Remainder
:IEEE 754 标准余数(符号与被除数相同)。
fmt.Println(math.Mod(10, 3)) // 输出: 1
fmt.Println(math.Remainder(10, 3)) // 输出: 1
fmt.Println(math.Mod(-10, 3)) // 输出: -1
fmt.Println(math.Remainder(-10, 3)) // 输出: -1
math.Cbrt
和 math.Sqrt
立方根和平方根。
fmt.Println(math.Sqrt(16)) // 输出: 4
fmt.Println(math.Cbrt(27)) // 输出: 3
2. 三角函数
所有函数参数为弧度(非角度)。
math.Sin
、math.Cos
、math.Tan
rad := math.Pi / 2
fmt.Println(math.Sin(rad)) // 输出: 1(近似值)
fmt.Println(math.Cos(rad)) // 输出: 6.123e-17(接近0)
math.Asin
、math.Acos
、math.Atan
反三角函数(返回弧度)。
fmt.Println(math.Asin(1)) // 输出: 1.5708(π/2)
3. 指数与对数
math.Exp
和 math.Log
自然指数和对数。
fmt.Println(math.Exp(2)) // 输出: ~7.389(e²)
fmt.Println(math.Log(7.389)) // 输出: ~2
math.Pow
和 math.Pow10
幂运算。
fmt.Println(math.Pow(2, 3)) // 输出: 8
fmt.Println(math.Pow10(3)) // 输出: 1000
math.Log10
和 math.Log2
以10或2为底的对数。
fmt.Println(math.Log10(1000)) // 输出: 3
fmt.Println(math.Log2(8)) // 输出: 3
4. 取整与截断
math.Ceil
和 math.Floor
向上和向下取整。
fmt.Println(math.Ceil(3.2)) // 输出: 4
fmt.Println(math.Floor(3.9)) // 输出: 3
math.Trunc
直接截断小数部分。
fmt.Println(math.Trunc(3.9)) // 输出: 3
math.Round
和 math.RoundToEven
四舍五入(RoundToEven
向最近的偶数舍入)。
fmt.Println(math.Round(2.5)) // 输出: 3
fmt.Println(math.RoundToEven(2.5)) // 输出: 2
5. 最大值与最小值
math.Max
和 math.Min
返回两个 float64
值的最大或最小值。
fmt.Println(math.Max(3, 5)) // 输出: 5
fmt.Println(math.Min(3, 5)) // 输出: 3
6. 特殊值处理
math.IsNaN
和 math.IsInf
检查是否为非数值或无穷大。
val := math.Log(-1) // 生成 NaN
fmt.Println(math.IsNaN(val)) // 输出: true
fmt.Println(math.IsInf(1/math.Inf(1), 0)) // 检查是否无穷大
math.Inf
和 math.NaN
生成无穷大或非数值。
posInf := math.Inf(1) // 正无穷
negInf := math.Inf(-1) // 负无穷
nan := math.NaN()
7. 特殊函数
math.Hypot
计算直角三角形的斜边长度。
fmt.Println(math.Hypot(3, 4)) // 输出: 5
math.Gamma
和 math.Erf
伽马函数和误差函数。
fmt.Println(math.Gamma(5)) // 输出: 24(4!)
fmt.Println(math.Erf(1)) // 输出: ~0.8427
8. 数学常量
常用常量
fmt.Println(math.Pi) // 输出: 3.141592653589793
fmt.Println(math.E) // 输出: 2.718281828459045
fmt.Println(math.Phi) // 输出: 1.618033988749895(黄金分割)
总结
- 核心功能:
- 基础运算:
Abs
,Mod
,Sqrt
,Pow
- 三角函数:
Sin
,Cos
,Asin
- 指数对数:
Exp
,Log
,Log10
- 取整处理:
Ceil
,Floor
,Round
- 特殊值:
NaN
,Inf
,IsNaN
- 常量:
Pi
,E
- 基础运算:
- 注意事项:
- 所有函数操作
float64
类型(需显式转换其他类型)。 - 三角函数参数为弧度(需将角度转换为弧度:
rad = degrees * π / 180
)。 - 处理特殊值(如
NaN
)时需用math.IsNaN
判断,不可直接比较。
- 所有函数操作