Go语言的模块提供了丰富的数学函数和常量,涵盖基本运算、三角函数、指数、对数、取整、特殊值等。以下是核心方法及示例说明:
1. 基本数学运算
math.Abs
取绝对值(仅)。- fmt.Println(math.Abs(-3.5)) // 输出: 3.5
- fmt.Println(math.Abs(4)) // 错误!需用 math.Abs(4.0)
复制代码 math.Mod 和 math.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
四舍五入(向最近的偶数舍入)。- fmt.Println(math.Round(2.5)) // 输出: 3
- fmt.Println(math.RoundToEven(2.5)) // 输出: 2
复制代码 5. 最大值与最小值
math.Max 和 math.Min
返回两个值的最大或最小值。- 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(黄金分割)
复制代码 总结
- 核心功能:
- 基础运算:,,,
- 三角函数:,,
- 指数对数:,,
- 取整处理:,,
- 特殊值:,,
- 常量:,
- 注意事项:
- 所有函数操作类型(需显式转换其他类型)。
- 三角函数参数为弧度(需将角度转换为弧度:)。
- 处理特殊值(如)时需用判断,不可直接比较。
到此这篇关于Go语言标准库中math模块详细功能介绍与示例代码的文章就介绍到这了,更多相关Go语言标准库math模块介绍内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源:互联网
免责声明:如果侵犯了您的权益,请联系站长(1277306191@qq.com),我们会及时删除侵权内容,谢谢合作! |
|