math

Math #

Abs 绝对值 #

func Abs(x float64) float64:返回指定数字的绝对值。适用于负数和正数,确保结果为非负数。

x := -5.5
fmt.Println(math.Abs(x)) // 输出: 5.5

Pow 幂运算 #

func Pow(x, y float64) float64:计算xy次幂。常用于指数运算。

base := 2.0
exponent := 3.0
fmt.Println(math.Pow(base, exponent)) // 输出: 8.0

Sqrt 平方根 #

func Sqrt(x float64) float64:返回x的平方根。适用于非负数。

num := 16.0
fmt.Println(math.Sqrt(num)) // 输出: 4.0

Sin 正弦 #

func Sin(x float64) float64:返回x的正弦值,x以弧度为单位。用于三角函数计算。

radian := math.Pi / 2
fmt.Println(math.Sin(radian)) // 输出: 1.0

Cos 余弦 #

func Cos(x float64) float64:返回x的余弦值,x以弧度为单位。

radian := math.Pi
fmt.Println(math.Cos(radian)) // 输出: -1.0

Tan 正切 #

func Tan(x float64) float64:返回x的正切值,x以弧度为单位。

radian := math.Pi / 4
fmt.Println(math.Tan(radian)) // 输出: 1.0

Log 对数 #

func Log(x float64) float64:返回x的自然对数(以e为底)。

num := 10.0
fmt.Println(math.Log(num)) // 输出: 2.302585...

Log10 常用对数 #

func Log10(x float64) float64:返回x的常用对数(以10为底)。

num := 100.0
fmt.Println(math.Log10(num)) // 输出: 2.0

Exp 指数 #

func Exp(x float64) float64:返回e^x的值。

exponent := 1.0
fmt.Println(math.Exp(exponent)) // 输出: 2.718281...

Max 最大值 #

func Max(x, y float64) float64:返回xy中的最大值。

a := 5.0
b := 10.0
fmt.Println(math.Max(a, b)) // 输出: 10.0

Min 最小值 #

func Min(x, y float64) float64:返回xy中的最小值。

a := 5.0
b := 10.0
fmt.Println(math.Min(a, b)) // 输出: 5.0

Ceil 向上取整 #

func Ceil(x float64) float64:返回大于或等于x的最小整数值。

num := 1.3
fmt.Println(math.Ceil(num)) // 输出: 2.0

Floor 向下取整 #

func Floor(x float64) float64:返回小于或等于x的最大整数值。

num := 1.7
fmt.Println(math.Floor(num)) // 输出: 1.0

Round 四舍五入 #

func Round(x float64) float64:返回x的四舍五入整数值。

num := 1.5
fmt.Println(math.Round(num)) // 输出: 2.0

Trunc 截断 #

func Trunc(x float64) float64:返回x的整数部分,直接截断小数。

num := 1.9
fmt.Println(math.Trunc(num)) // 输出: 1.0

Hypot 直角三角形斜边 #

func Hypot(x, y float64) float64:返回直角三角形斜边的长度,计算公式为√(x² + y²)

x := 3.0
y := 4.0
fmt.Println(math.Hypot(x, y)) // 输出: 5.0

Mod 取模 #

func Mod(x, y float64) float64:返回xy的浮点数余数。

x := 5.5
y := 2.0
fmt.Println(math.Mod(x, y)) // 输出: 1.5

Cbrt 立方根 #

func Cbrt(x float64) float64:返回x的立方根。

num := 27.0
fmt.Println(math.Cbrt(num)) // 输出: 3.0

Exp2 二次幂 #

func Exp2(x float64) float64:返回2^x的值。

exponent := 3.0
fmt.Println(math.Exp2(exponent)) // 输出: 8.0