1. 程式人生 > 其它 >go 常用標準庫 數學計算

go 常用標準庫 數學計算

go 常用標準庫

1.1 數學常量

math.E	//自然對數的底,2.718281828459045
math.Pi	//圓周率,3.141592653589793
math.Phi	//黃金分割,長/短,1.618033988749895
math.MaxInt	//9223372036854775807
uint64(math.MaxUint)	//得先把MaxUint轉成uint64才能輸出,18446744073709551615
math.MaxFloat64	//1.7976931348623157e+308
math.SmallestNonzeroFloat64	//最小的非0且正的浮點數,5e-324

2.1 NaN(Not a Number)

f := math.NaN()
math.IsNaN(f)

3.1 常用函式

math.Ceil(1.1)	//向上取整,2
math.Floor(1.9)	//向下取整,1。 math.Floor(-1.9)=-2
math.Trunc(1.9)	//取整數部分,1
math.Modf(2.5)	//返回整數部分和小數部分,2  0.5
math.Abs(-2.6)	//絕對值,2.6
math.Max(4, 8)	//取二者的較大者,8
math.Min(4, 8)	//取二者的較小者,4
math.Mod(6.5, 3.5)	//x-Trunc(x/y)*y結果的正負號和x相同,3
math.Sqrt(9)		//開平方,3
math.Cbrt(9)		//開三次方,2.08008

4.1 三角函式

math.Sin(1)
math.Cos(1)
math.Tan(1)
math.Tanh(1)

5.1 對數和指數

math.Log(5)	//自然對數,1.60943
math.Log1p(4)	//等價於Log(1+p),確保結果為正數,1.60943
math.Log10(100)	//以10為底數,取對數,2
math.Log2(8)	//以2為底數,取對數,3
math.Pow(3, 2)	//x^y,9
math.Pow10(2)	//10^x,100
math.Exp(2)	//e^x,7.389

6.1 隨機數生成器

//建立一個Rand
source := rand.NewSource(1) //seed相同的情況下,隨機數生成器產生的數列是相同的
rander := rand.New(source)
for i := 0; i < 10; i++ {
    fmt.Printf("%d ", rander.Intn(100))
}
fmt.Println()
source.Seed(1) //必須重置一下Seed
rander2 := rand.New(source)
for i := 0; i < 10; i++ {
    fmt.Printf("%d ", rander2.Intn(100))
}
fmt.Println()

//使用全域性Rand
rand.Seed(1)                //如果對兩次執行沒有一致性要求,可以不設seed
fmt.Println(rand.Int())     //隨機生成一個整數
fmt.Println(rand.Float32()) //隨機生成一個浮點數
fmt.Println(rand.Intn(100)) //100以內的隨機整數,[0,100)
fmt.Println(rand.Perm(100)) //把[0,100)上的整數隨機打亂
arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
rand.Shuffle(len(arr), func(i, j int) { //隨機打亂一個給定的slice
    arr[i], arr[j] = arr[j], arr[i]
})
fmt.Println(arr)