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

匯入


  1. import "math"

常用 API


常數:Pi、E 與整數上下限


math 定義了常用的數學常數(Pi、E、Sqrt2...)與各整數型別的範圍(MaxInt64、MinInt8、MaxUint32...)。浮點數的範圍則有 MaxFloat64(最大有限值)與 SmallestNonzeroFloat64(最小的正數)。
這些都是無型別常數(觀念見 常數與 iota),可以直接拿來跟任何數值型別比較。MaxInt/MinInt/MaxUint 會依平台的 int 寬度而定,在 64 位元平台上等於 MaxInt64 等。
簽名:
  1. const (
  2. E = 2.71828182845904523536028747135266249775724709369995957496696763
  3. Pi = 3.14159265358979323846264338327950288419716939937510582097494459
  4. )
  5. const (
  6. MaxInt64 = 1<<63 - 1
  7. MaxUint32 = 1<<32 - 1
  8. )
  9. const MaxFloat64 = 0x1p1023 * (1 + (1 - 0x1p-52))

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. fmt.Println("Pi:", math.Pi)
  8. fmt.Println("E:", math.E)
  9. fmt.Println("MaxInt8:", math.MaxInt8)
  10. fmt.Println("MinInt8:", math.MinInt8)
  11. fmt.Println("MaxInt64:", math.MaxInt64)
  12. fmt.Println("MaxUint32:", uint32(math.MaxUint32))
  13. fmt.Println("MaxFloat64:", math.MaxFloat64)
  14. var n int8 = 100
  15. if int(n)+50 > math.MaxInt8 {
  16. fmt.Println("100 + 50 放不進 int8")
  17. }
  18. }

輸出:
  1. Pi: 3.141592653589793
  2. E: 2.718281828459045
  3. MaxInt8: 127
  4. MinInt8: -128
  5. MaxInt64: 9223372036854775807
  6. MaxUint32: 4294967295
  7. MaxFloat64: 1.7976931348623157e+308
  8. 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 檢查。
簽名:
  1. func Abs(x float64) float64
  2. func Sqrt(x float64) float64
  3. func Cbrt(x float64) float64
  4. func Pow(x, y float64) float64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. fmt.Println(math.Abs(-3.5))
  8. fmt.Println(math.Sqrt(16))
  9. fmt.Println(math.Sqrt(2))
  10. fmt.Println(math.Cbrt(-27))
  11. fmt.Println(math.Pow(2, 10))
  12. fmt.Println(math.Pow(9, 0.5))
  13. fmt.Println(math.Sqrt(-1))
  14. n := 49
  15. root := int(math.Sqrt(float64(n)))
  16. fmt.Println("49 的平方根:", root)
  17. }

輸出:
  1. 3.5
  2. 4
  3. 1.4142135623730951
  4. -3
  5. 1024
  6. 3
  7. NaN
  8. 49 的平方根: 7

Floor、Ceil、Trunc、Round、RoundToEven


把小數變成整數有好幾種方式,差別在「往哪個方向取」:
函式規則2.5-2.5
Floor往負無限大(地板)2-3
Ceil往正無限大(天花板)3-2
Trunc直接去掉小數(往 0)2-2
Round四捨五入,剛好一半時遠離 03-3
RoundToEven剛好一半時取偶數(銀行家捨入)2-2

回傳值仍是 float64,需要整數時再轉型。直接寫 int(x) 的效果等同 Trunc。
簽名:
  1. func Floor(x float64) float64
  2. func Ceil(x float64) float64
  3. func Trunc(x float64) float64
  4. func Round(x float64) float64
  5. func RoundToEven(x float64) float64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. for _, x := range []float64{2.5, -2.5, 3.7, 3.5} {
  8. fmt.Printf("x=%5.1f Floor=%3.0f Ceil=%3.0f Trunc=%3.0f Round=%3.0f RoundToEven=%3.0f\n",
  9. x, math.Floor(x), math.Ceil(x), math.Trunc(x), math.Round(x), math.RoundToEven(x))
  10. }
  11. price := 12.3456
  12. fmt.Println(math.Round(price*100) / 100)
  13. fmt.Println(int(math.Round(2.6)))
  14. }

輸出:
  1. x= 2.5 Floor= 2 Ceil= 3 Trunc= 2 Round= 3 RoundToEven= 2
  2. x= -2.5 Floor= -3 Ceil= -2 Trunc= -2 Round= -3 RoundToEven= -2
  3. x= 3.7 Floor= 3 Ceil= 4 Trunc= 3 Round= 4 RoundToEven= 4
  4. x= 3.5 Floor= 3 Ceil= 4 Trunc= 3 Round= 4 RoundToEven= 4
  5. 12.35
  6. 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)。
簽名:
  1. func Max(x, y float64) float64
  2. func Min(x, y float64) float64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. fmt.Println(math.Max(3, 7))
  8. fmt.Println(math.Min(3, 7))
  9. fmt.Println(math.Max(1, math.NaN()))
  10. fmt.Println(max(3, 9, 5))
  11. fmt.Println(min(4, 2, 8))
  12. fmt.Println(max("apple", "banana"))
  13. }

輸出:
  1. 7
  2. 3
  3. NaN
  4. 9
  5. 2
  6. banana

Inf、NaN、IsInf、IsNaN


  • Inf(sign):sign >= 0 回傳 +Inf,否則回傳 -Inf
  • NaN():回傳 NaN
  • IsInf(x, sign):sign 為 1 檢查 +Inf、-1 檢查 -Inf、0 兩者都算
  • IsNaN(x):是否為 NaN

注意:NaN 和任何值比較都是 false,連 x == x 都是 false,所以檢查 NaN 一定要用 IsNaN。另外,浮點數除以 0 不會 panic,而是得到 Inf 或 NaN(整數除以 0 才會 panic)。
簽名:
  1. func Inf(sign int) float64
  2. func NaN() float64
  3. func IsInf(f float64, sign int) bool
  4. func IsNaN(f float64) (is bool)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. zero := 0.0
  8. a := 1 / zero
  9. b := -1 / zero
  10. c := zero / zero
  11. fmt.Println(a, b, c)
  12. fmt.Println(math.IsInf(a, 1), math.IsInf(b, -1), math.IsInf(b, 0))
  13. fmt.Println(c == c, math.IsNaN(c))
  14. fmt.Println(math.Inf(1) > math.MaxFloat64)
  15. fmt.Println(math.NaN() == math.NaN())
  16. }

輸出:
  1. +Inf -Inf NaN
  2. true true true
  3. false true
  4. true
  5. false

Mod 與 Modf


  • Mod(x, y):浮點數的餘數,結果的正負號跟 x 相同(整數用 % 即可,浮點數不能用 %)
  • Modf(f):把數字拆成整數部分與小數部分,兩者正負號都跟 f 相同

簽名:
  1. func Mod(x, y float64) float64
  2. func Modf(f float64) (integer float64, fractional float64)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. fmt.Println(math.Mod(7.5, 2))
  8. fmt.Println(math.Mod(-7.5, 2))
  9. i, f := math.Modf(3.75)
  10. fmt.Println(i, f)
  11. i, f = math.Modf(-3.75)
  12. fmt.Println(i, f)
  13. angle := math.Mod(370, 360)
  14. fmt.Println("370 度等於", angle, "度")
  15. }

輸出:
  1. 1.5
  2. -1.5
  3. 3 0.75
  4. -3 -0.75
  5. 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。
簽名:
  1. func Log(x float64) float64
  2. func Log2(x float64) float64
  3. func Log10(x float64) float64
  4. func Exp(x float64) float64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. fmt.Println(math.Log(math.E))
  8. fmt.Println(math.Log2(1024))
  9. fmt.Println(math.Log10(1000))
  10. fmt.Println(math.Exp(0))
  11. fmt.Printf("%.4f\n", math.Exp(1))
  12. fmt.Println(math.Log(0), math.Log(-1))
  13. n := 1_000_000.0
  14. fmt.Println("位數:", int(math.Log10(n))+1)
  15. }

輸出:
  1. 1
  2. 10
  3. 3
  4. 1
  5. 2.7183
  6. -Inf NaN
  7. 位數: 7

Sin、Cos、Atan2、Hypot


三角函數的角度單位是弧度(radian),不是度。換算公式:弧度 = 度 × π / 180。
  • Sin、Cos、Tan:三角函數
  • Atan2(y, x):由座標 (x, y) 求角度,會依象限給出正確結果
  • Hypot(p, q):Sqrt(p*p + q*q),求直角三角形斜邊或兩點距離,避免中間值溢位

簽名:
  1. func Sin(x float64) float64
  2. func Cos(x float64) float64
  3. func Atan2(y, x float64) float64
  4. func Hypot(p, q float64) float64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. deg := 30.0
  8. rad := deg * math.Pi / 180
  9. fmt.Printf("sin(30°) = %.4f\n", math.Sin(rad))
  10. fmt.Printf("cos(60°) = %.4f\n", math.Cos(60*math.Pi/180))
  11. angle := math.Atan2(1, -1) * 180 / math.Pi
  12. fmt.Println("點 (-1, 1) 的角度:", angle)
  13. fmt.Println("3-4-5 三角形斜邊:", math.Hypot(3, 4))
  14. x1, y1, x2, y2 := 1.0, 2.0, 4.0, 6.0
  15. fmt.Println("兩點距離:", math.Hypot(x2-x1, y2-y1))
  16. }

輸出:
  1. sin(30°) = 0.5000
  2. cos(60°) = 0.5000
  3. 點 (-1, 1) 的角度: 135
  4. 3-4-5 三角形斜邊: 5
  5. 兩點距離: 5

Float64bits 與 Float64frombits


把 float64 的 64 個位元原封不動地當成 uint64 讀出(或反過來)。用在需要看浮點數內部表示(IEEE 754 格式)、或把浮點數寫進二進位格式的時候。
這不是數值轉換:uint64(1.0) 得到 1,而 Float64bits(1.0) 得到的是 1.0 的位元樣式。
簽名:
  1. func Float64bits(f float64) uint64
  2. func Float64frombits(b uint64) float64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. b := math.Float64bits(1.0)
  8. fmt.Printf("%#016x\n", b)
  9. fmt.Printf("%064b\n", b)
  10. fmt.Println(math.Float64frombits(0x4000000000000000))
  11. fmt.Println(math.Float64bits(0.0) == math.Float64bits(math.Copysign(0, -1)))
  12. fmt.Println(0.0 == math.Copysign(0, -1))
  13. }

輸出:
  1. 0x3ff0000000000000
  2. 0011111111110000000000000000000000000000000000000000000000000000
  3. 2
  4. false
  5. 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

資料來源