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
判断,不可直接比较。
- 所有函数操作
到此这篇关于go语言标准库中math模块详细功能介绍与示例代码的文章就介绍到这了,更多相关go语言标准库math模块介绍内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论