math
最後更新
math 套件提供浮點數的基本數學函式與常數:開根號、次方、取整、三角函數、對數,以及各整數型別的上下限。這個套件做什麼
寫程式時常會遇到「算平方根」「四捨五入到整數」「這個 int64 最大能放多少」這類問題,
math 就是答案所在。幾個新手要先知道的特性:
- 幾乎所有函式都吃
float64、回傳float64。手上是int時要先轉型:math.Sqrt(float64(n)) - 浮點數有三個特殊值:正無限大(+Inf)、負無限大(-Inf)、非數字(NaN,Not a Number)。
math的函式遇到不合法的輸入(例如負數開根號)通常不會 panic,而是回傳 NaN 或 Inf - 浮點數本身有精度限制,觀念請見 浮點數與複數
和相近套件的差別:
| 需求 | 用哪個 |
|---|---|
| float64 的一般數學運算 | math |
| 超過 int64 範圍的整數、任意精度小數 | math/big |
| 位元計數、旋轉、帶進位加法 | math/bits |
| 亂數 | math/rand/v2 |
| 複數運算 | math/cmplx |
匯入
- import "math"
常用 API
常數:Pi、E 與整數上下限
math 定義了常用的數學常數(Pi、E、Sqrt2...)與各整數型別的範圍(MaxInt64、MinInt8、MaxUint32...)。浮點數的範圍則有 MaxFloat64(最大有限值)與 SmallestNonzeroFloat64(最小的正數)。這些都是無型別常數(觀念見 常數與 iota),可以直接拿來跟任何數值型別比較。
MaxInt/MinInt/MaxUint 會依平台的 int 寬度而定,在 64 位元平台上等於 MaxInt64 等。簽名:
- const (
- E = 2.71828182845904523536028747135266249775724709369995957496696763
- Pi = 3.14159265358979323846264338327950288419716939937510582097494459
- )
- const (
- MaxInt64 = 1<<63 - 1
- MaxUint32 = 1<<32 - 1
- )
- const MaxFloat64 = 0x1p1023 * (1 + (1 - 0x1p-52))
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- fmt.Println("Pi:", math.Pi)
- fmt.Println("E:", math.E)
- fmt.Println("MaxInt8:", math.MaxInt8)
- fmt.Println("MinInt8:", math.MinInt8)
- fmt.Println("MaxInt64:", math.MaxInt64)
- fmt.Println("MaxUint32:", uint32(math.MaxUint32))
- fmt.Println("MaxFloat64:", math.MaxFloat64)
- var n int8 = 100
- if int(n)+50 > math.MaxInt8 {
- fmt.Println("100 + 50 放不進 int8")
- }
- }
輸出:
- Pi: 3.141592653589793
- E: 2.718281828459045
- MaxInt8: 127
- MinInt8: -128
- MaxInt64: 9223372036854775807
- MaxUint32: 4294967295
- MaxFloat64: 1.7976931348623157e+308
- 100 + 50 放不進 int8
注意:
fmt.Println(math.MaxUint64) 會編譯失敗,因為無型別常數預設轉成 int,而 int 放不下。要印時寫 uint64(math.MaxUint64)。Abs、Sqrt、Pow、Cbrt
Abs(x):絕對值Sqrt(x):平方根Cbrt(x):立方根,負數也能算Pow(x, y):x 的 y 次方
注意:
Sqrt 給負數會回傳 NaN,不會 panic;計算結果要用 math.IsNaN 檢查。簽名:
- func Abs(x float64) float64
- func Sqrt(x float64) float64
- func Cbrt(x float64) float64
- func Pow(x, y float64) float64
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- fmt.Println(math.Abs(-3.5))
- fmt.Println(math.Sqrt(16))
- fmt.Println(math.Sqrt(2))
- fmt.Println(math.Cbrt(-27))
- fmt.Println(math.Pow(2, 10))
- fmt.Println(math.Pow(9, 0.5))
- fmt.Println(math.Sqrt(-1))
- n := 49
- root := int(math.Sqrt(float64(n)))
- fmt.Println("49 的平方根:", root)
- }
輸出:
- 3.5
- 4
- 1.4142135623730951
- -3
- 1024
- 3
- NaN
- 49 的平方根: 7
Floor、Ceil、Trunc、Round、RoundToEven
把小數變成整數有好幾種方式,差別在「往哪個方向取」:
| 函式 | 規則 | 2.5 | -2.5 |
|---|---|---|---|
Floor | 往負無限大(地板) | 2 | -3 |
Ceil | 往正無限大(天花板) | 3 | -2 |
Trunc | 直接去掉小數(往 0) | 2 | -2 |
Round | 四捨五入,剛好一半時遠離 0 | 3 | -3 |
RoundToEven | 剛好一半時取偶數(銀行家捨入) | 2 | -2 |
回傳值仍是
float64,需要整數時再轉型。直接寫 int(x) 的效果等同 Trunc。簽名:
- func Floor(x float64) float64
- func Ceil(x float64) float64
- func Trunc(x float64) float64
- func Round(x float64) float64
- func RoundToEven(x float64) float64
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- for _, x := range []float64{2.5, -2.5, 3.7, 3.5} {
- fmt.Printf("x=%5.1f Floor=%3.0f Ceil=%3.0f Trunc=%3.0f Round=%3.0f RoundToEven=%3.0f\n",
- x, math.Floor(x), math.Ceil(x), math.Trunc(x), math.Round(x), math.RoundToEven(x))
- }
- price := 12.3456
- fmt.Println(math.Round(price*100) / 100)
- fmt.Println(int(math.Round(2.6)))
- }
輸出:
- x= 2.5 Floor= 2 Ceil= 3 Trunc= 2 Round= 3 RoundToEven= 2
- x= -2.5 Floor= -3 Ceil= -2 Trunc= -2 Round= -3 RoundToEven= -2
- x= 3.7 Floor= 3 Ceil= 4 Trunc= 3 Round= 4 RoundToEven= 4
- x= 3.5 Floor= 3 Ceil= 4 Trunc= 3 Round= 4 RoundToEven= 4
- 12.35
- 3
「四捨五入到小數第二位」常見寫法是先乘 100、
Round、再除 100;但只是要「顯示」兩位小數的話,用 fmt.Printf("%.2f", x) 就夠了。Max、Min 與內建 max、min
math.Max/math.Min 只接受兩個 float64,而且會正確處理 NaN 與 ±0 的特殊情況。Go 1.21 起語言內建
max/min 函式,可以接受任意多個參數,也支援整數與字串。一般比大小直接用內建版本即可;處理浮點數時兩者對 NaN 的規則相同(只要有一個是 NaN,結果就是 NaN)。簽名:
- func Max(x, y float64) float64
- func Min(x, y float64) float64
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- fmt.Println(math.Max(3, 7))
- fmt.Println(math.Min(3, 7))
- fmt.Println(math.Max(1, math.NaN()))
- fmt.Println(max(3, 9, 5))
- fmt.Println(min(4, 2, 8))
- fmt.Println(max("apple", "banana"))
- }
輸出:
- 7
- 3
- NaN
- 9
- 2
- banana
Inf、NaN、IsInf、IsNaN
Inf(sign):sign >= 0回傳 +Inf,否則回傳 -InfNaN():回傳 NaNIsInf(x, sign):sign為 1 檢查 +Inf、-1 檢查 -Inf、0 兩者都算IsNaN(x):是否為 NaN
注意:NaN 和任何值比較都是 false,連
x == x 都是 false,所以檢查 NaN 一定要用 IsNaN。另外,浮點數除以 0 不會 panic,而是得到 Inf 或 NaN(整數除以 0 才會 panic)。簽名:
- func Inf(sign int) float64
- func NaN() float64
- func IsInf(f float64, sign int) bool
- func IsNaN(f float64) (is bool)
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- zero := 0.0
- a := 1 / zero
- b := -1 / zero
- c := zero / zero
- fmt.Println(a, b, c)
- fmt.Println(math.IsInf(a, 1), math.IsInf(b, -1), math.IsInf(b, 0))
- fmt.Println(c == c, math.IsNaN(c))
- fmt.Println(math.Inf(1) > math.MaxFloat64)
- fmt.Println(math.NaN() == math.NaN())
- }
輸出:
- +Inf -Inf NaN
- true true true
- false true
- true
- false
Mod 與 Modf
Mod(x, y):浮點數的餘數,結果的正負號跟x相同(整數用%即可,浮點數不能用%)Modf(f):把數字拆成整數部分與小數部分,兩者正負號都跟f相同
簽名:
- func Mod(x, y float64) float64
- func Modf(f float64) (integer float64, fractional float64)
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- fmt.Println(math.Mod(7.5, 2))
- fmt.Println(math.Mod(-7.5, 2))
- i, f := math.Modf(3.75)
- fmt.Println(i, f)
- i, f = math.Modf(-3.75)
- fmt.Println(i, f)
- angle := math.Mod(370, 360)
- fmt.Println("370 度等於", angle, "度")
- }
輸出:
- 1.5
- -1.5
- 3 0.75
- -3 -0.75
- 370 度等於 10 度
Log、Log2、Log10、Exp
Log(x):自然對數(以 e 為底)Log2(x)、Log10(x):以 2、以 10 為底Exp(x):e 的 x 次方,是Log的反運算
注意:
Log(0) 回傳 -Inf,Log 給負數回傳 NaN。簽名:
- func Log(x float64) float64
- func Log2(x float64) float64
- func Log10(x float64) float64
- func Exp(x float64) float64
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- fmt.Println(math.Log(math.E))
- fmt.Println(math.Log2(1024))
- fmt.Println(math.Log10(1000))
- fmt.Println(math.Exp(0))
- fmt.Printf("%.4f\n", math.Exp(1))
- fmt.Println(math.Log(0), math.Log(-1))
- n := 1_000_000.0
- fmt.Println("位數:", int(math.Log10(n))+1)
- }
輸出:
- 1
- 10
- 3
- 1
- 2.7183
- -Inf NaN
- 位數: 7
Sin、Cos、Atan2、Hypot
三角函數的角度單位是弧度(radian),不是度。換算公式:弧度 = 度 × π / 180。
Sin、Cos、Tan:三角函數Atan2(y, x):由座標 (x, y) 求角度,會依象限給出正確結果Hypot(p, q):Sqrt(p*p + q*q),求直角三角形斜邊或兩點距離,避免中間值溢位
簽名:
- func Sin(x float64) float64
- func Cos(x float64) float64
- func Atan2(y, x float64) float64
- func Hypot(p, q float64) float64
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- deg := 30.0
- rad := deg * math.Pi / 180
- fmt.Printf("sin(30°) = %.4f\n", math.Sin(rad))
- fmt.Printf("cos(60°) = %.4f\n", math.Cos(60*math.Pi/180))
- angle := math.Atan2(1, -1) * 180 / math.Pi
- fmt.Println("點 (-1, 1) 的角度:", angle)
- fmt.Println("3-4-5 三角形斜邊:", math.Hypot(3, 4))
- x1, y1, x2, y2 := 1.0, 2.0, 4.0, 6.0
- fmt.Println("兩點距離:", math.Hypot(x2-x1, y2-y1))
- }
輸出:
- sin(30°) = 0.5000
- cos(60°) = 0.5000
- 點 (-1, 1) 的角度: 135
- 3-4-5 三角形斜邊: 5
- 兩點距離: 5
Float64bits 與 Float64frombits
把
float64 的 64 個位元原封不動地當成 uint64 讀出(或反過來)。用在需要看浮點數內部表示(IEEE 754 格式)、或把浮點數寫進二進位格式的時候。這不是數值轉換:
uint64(1.0) 得到 1,而 Float64bits(1.0) 得到的是 1.0 的位元樣式。簽名:
- func Float64bits(f float64) uint64
- func Float64frombits(b uint64) float64
範例:
- package main
- import (
- "fmt"
- "math"
- )
- func main() {
- b := math.Float64bits(1.0)
- fmt.Printf("%#016x\n", b)
- fmt.Printf("%064b\n", b)
- fmt.Println(math.Float64frombits(0x4000000000000000))
- fmt.Println(math.Float64bits(0.0) == math.Float64bits(math.Copysign(0, -1)))
- fmt.Println(0.0 == math.Copysign(0, -1))
- }
輸出:
- 0x3ff0000000000000
- 0011111111110000000000000000000000000000000000000000000000000000
- 2
- false
- true
最後兩行說明 +0 與 -0 數值相等,但位元樣式不同。
重點整理
math的函式幾乎都以float64進出,整數要先轉型- 不合法輸入通常回傳 NaN 或 ±Inf 而非 panic;檢查 NaN 必須用
math.IsNaN,因為NaN != NaN - 取整有五種:
Floor、Ceil、Trunc、Round、RoundToEven,差在方向與一半時的規則 - 三角函數使用弧度;距離用
Hypot - 比大小優先用內建
max/min(Go 1.21 起) - 整數範圍常數如
math.MaxInt64是無型別常數,印MaxUint64時要明確轉成uint64