Math
suggest changeGo's standard library splits math functionality across a few packages:
| Package | What's in it |
|---|---|
math |
constants, rounding, powers, roots, logarithms, trigonometry, Inf and NaN for float64 |
math/bits |
bit counting, rotation, and add/multiply with carry for unsigned integers |
math/rand/v2 |
pseudo-random numbers |
math/cmplx |
functions for complex128 |
math/big |
arbitrary-precision integers, floats, and rationals |
Almost every function in math takes and returns float64. There are no float32 or integer versions, so you convert to and from float64 as needed.
Arithmetic operators, integer division, and overflow are covered in Operators. Numbers that don't fit in 64 bits are covered in big.Int, big.Float, and big.Rat.
Constants
Package math defines common mathematical constants and the limits of the numeric types:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("Pi: ", math.Pi)
fmt.Println("E: ", math.E)
fmt.Println("Sqrt2: ", math.Sqrt2)
fmt.Println("Phi: ", math.Phi)
fmt.Println("MaxInt: ", math.MaxInt)
fmt.Println("MinInt8:", math.MinInt8)
fmt.Println("MaxUint32:", math.MaxUint32)
fmt.Println("MaxFloat64:", math.MaxFloat64)
fmt.Println("SmallestNonzeroFloat64:", math.SmallestNonzeroFloat64)
fmt.Println("MaxFloat32:", math.MaxFloat32)
// untyped constants have arbitrary precision
var f32 float32 = math.Pi
fmt.Println(f32)
fmt.Printf("%.20f\n", math.Pi)
}
Pi: 3.141592653589793
E: 2.718281828459045
Sqrt2: 1.4142135623730951
Phi: 1.618033988749895
MaxInt: 9223372036854775807
MinInt8: -128
MaxUint32: 4294967295
MaxFloat64: 1.7976931348623157e+308
SmallestNonzeroFloat64: 5e-324
MaxFloat32: 3.4028234663852886e+38
3.1415927
3.14159265358979311600
The constants are untyped and have much higher precision than float64. For example math.Pi is defined with 63 decimal digits. It gets rounded only when you assign it to a variable, so the same constant works as float32 or float64.
Use math.MaxInt64, math.MinInt32, math.MaxUint16 and the rest to check ranges before converting between integer types.
Basic functions
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Abs(-3.5))
fmt.Println(math.Sqrt(2))
fmt.Println(math.Sqrt(-1))
fmt.Println(math.Cbrt(27))
fmt.Println(math.Pow(2, 10))
fmt.Println(math.Pow(2, 0.5))
fmt.Println(math.Pow10(3))
fmt.Println(math.Hypot(3, 4))
fmt.Println(math.Max(3, 7), math.Min(3, 7))
fmt.Println(max(3, 7), min(2.5, 1, 4))
fmt.Println(math.Dim(10, 3), math.Dim(3, 10))
fmt.Println(math.FMA(2, 3, 4))
}
3.5
1.4142135623730951
NaN
3
1024
1.4142135623730951
1000
5
7 3
7 1
7 0
10
A few things to note:
math.Sqrtof a negative number returnsNaN, not an error and not a panicmath.Pow10(n)is faster and more accurate thanmath.Pow(10, n)math.Hypot(x, y)computessqrt(x*x + y*y)without overflowing for largexandymath.Dim(x, y)ismax(x-y, 0)math.FMA(x, y, z)computesx*y + zwith a single rounding
Since Go 1.21 there are built-in min and max functions. They work with any ordered type (integers, floats, strings) and any number of arguments, so you rarely need math.Min and math.Max. They handle edge cases the same way as math.Max and math.Min: if any argument is NaN, the result is NaN, and -0 is considered smaller than +0.
Rounding
There are 5 rounding functions. They differ in how they handle the fractional part and negative numbers:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Printf("%6s %6s %6s %6s %6s %12s\n", "x", "Floor", "Ceil", "Trunc", "Round", "RoundToEven")
for _, x := range []float64{2.4, 2.5, 3.5, -2.5, -2.7} {
fmt.Printf("%6.1f %6.1f %6.1f %6.1f %6.1f %12.1f\n",
x, math.Floor(x), math.Ceil(x), math.Trunc(x), math.Round(x), math.RoundToEven(x))
}
}
x Floor Ceil Trunc Round RoundToEven
2.4 2.0 3.0 2.0 2.0 2.0
2.5 2.0 3.0 2.0 3.0 2.0
3.5 3.0 4.0 3.0 4.0 4.0
-2.5 -3.0 -2.0 -2.0 -3.0 -2.0
-2.7 -3.0 -2.0 -2.0 -3.0 -3.0
Floorrounds down, towards negative infinityCeilrounds up, towards positive infinityTruncdrops the fractional part, i.e. rounds towards zeroRoundrounds to the nearest integer, halves away from zero (2.5becomes3,-2.5becomes-3)RoundToEvenrounds to the nearest integer, halves to the even neighbour. This is "banker's rounding". It avoids the upward bias thatRoundhas when you round a lot of values
All of them return float64, not an integer.
Rounding to decimal places and converting to int
There's no function to round to N decimal places. You can multiply, round, and divide:
package main
import (
"fmt"
"math"
"strconv"
)
func roundTo(x float64, places int) float64 {
p := math.Pow10(places)
return math.Round(x*p) / p
}
func main() {
fmt.Println(roundTo(3.14159, 2))
fmt.Println(roundTo(1234.5678, -2))
fmt.Println(roundTo(1.005, 2))
// for display, format instead of rounding
fmt.Printf("%.2f\n", 3.14159)
fmt.Println(strconv.FormatFloat(3.14159, 'f', 2, 64))
// converting float to int truncates towards zero
x := -7.9
fmt.Println(int(x), int(math.Round(x)), int(math.Floor(x)))
}
3.14
1200
1
3.14
3.14
-7 -8 -8
roundTo(1.005, 2) returns 1, not 1.01. That's because 1.005 can't be represented exactly in binary. The closest float64 is 1.00499999999999989..., which correctly rounds down.
Rounding to decimal places for display is usually a mistake. Keep the full value and round only when formatting it with %.2f or strconv.FormatFloat. See Floating-point numbers for details on formatting. For money, don't use floats at all: store the amount as an integer number of cents.
Converting a float to an integer with int(x) truncates towards zero. To round, call math.Round first. If the float value is out of range of the target integer type (or is NaN or Inf), the result of the conversion is implementation-specific. Check the range yourself if the value comes from untrusted input.
Integer math
math doesn't have integer versions of Abs, Pow, etc. Converting to float64 and back works for small values, but float64 has only 53 bits of mantissa, so it loses precision for integers larger than 2^53. It's better to write small helpers. With generics, one function works for all integer types:
package main
import (
"cmp"
"fmt"
)
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
func Abs[T Integer](x T) T {
if x < 0 {
return -x
}
return x
}
// IPow computes base**exp using exponentiation by squaring.
func IPow(base, exp int) int {
result := 1
for exp > 0 {
if exp&1 == 1 {
result *= base
}
base *= base
exp >>= 1
}
return result
}
// CeilDiv returns ceil(a/b) for positive a and b.
func CeilDiv(a, b int) int {
return (a + b - 1) / b
}
func Clamp[T cmp.Ordered](v, lo, hi T) T {
return min(max(v, lo), hi)
}
func GCD(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return Abs(a)
}
func main() {
fmt.Println(Abs(-42), Abs(int8(-5)))
fmt.Println(IPow(3, 4), IPow(2, 62))
fmt.Println(CeilDiv(10, 3), CeilDiv(9, 3))
fmt.Println(Clamp(150, 0, 100), Clamp(-0.5, 0.0, 1.0))
fmt.Println(GCD(48, 18), GCD(-12, 8))
}
42 5
81 4611686018427387904
4 3
100 0
6 4
IPow uses exponentiation by squaring, which needs O(log exp) multiplications. It silently overflows like any other integer arithmetic.
CeilDiv is a common idiom for "how many pages do I need for N items".
Note that Abs(math.MinInt64) is still math.MinInt64, because +9223372036854775808 doesn't fit in int64.
For bit-level operations on integers (counting set bits, leading zeros, rotations, overflow-detecting addition and multiplication) use package math/bits, shown in Operators.
Remainder and modulo
The % operator only works on integers. For floats there are math.Mod and math.Remainder:
package main
import (
"fmt"
"math"
)
func mod(a, n int) int {
return ((a % n) + n) % n
}
func main() {
fmt.Println(math.Mod(7.5, 2), math.Mod(-7.5, 2))
fmt.Println(math.Remainder(7.5, 2), math.Remainder(-7.5, 2))
ip, frac := math.Modf(3.75)
fmt.Println(ip, frac)
ip, frac = math.Modf(-3.75)
fmt.Println(ip, frac)
fmt.Println(-7%3, mod(-7, 3))
// day of week 10 days before Wednesday (3)
fmt.Println(mod(3-10, 7))
}
1.5 -1.5
-0.5 0.5
3 0.75
-3 -0.75
-1 2
0
math.Mod(x, y)has the sign ofx, like%for integersmath.Remainder(x, y)is the IEEE 754 remainder:x - n*ywherenisx/yrounded to the nearest integer. The result can be negative even when both arguments are positivemath.Modf(x)splits a float into its integer and fractional parts, both with the sign ofx
In Go -7 % 3 is -1. If you need a result that's always in the range [0, n) (for example for wrapping array indexes or days of the week), use ((a % n) + n) % n.
Exponents and logarithms
package main
import (
"fmt"
"math"
)
func logBase(x, base float64) float64 {
return math.Log(x) / math.Log(base)
}
func main() {
fmt.Println(math.Exp(1))
fmt.Println(math.Log(math.E))
fmt.Println(math.Log2(1024), math.Log10(0.001))
fmt.Println(logBase(81, 3))
fmt.Println(math.Exp2(10))
fmt.Println(math.Log(0), math.Log(-1))
// Log1p and Expm1 stay accurate for tiny x
x := 1e-15
fmt.Println(math.Log(1+x), math.Log1p(x))
fmt.Println(math.Exp(x)-1, math.Expm1(x))
// compound interest: 1000 at 5% for 10 years
fmt.Printf("%.2f\n", 1000*math.Pow(1.05, 10))
// continuous compounding
fmt.Printf("%.2f\n", 1000*math.Exp(0.05*10))
}
2.718281828459045
1
10 -3
4.000000000000001
1024
-Inf NaN
1.110223024625156e-15 9.999999999999995e-16
1.1102230246251565e-15 1.0000000000000007e-15
1628.89
1648.72
math.Logis the natural logarithm (basee)math.Log2andmath.Log10are base 2 and base 10. They're more accurate thanmath.Log(x) / math.Log(2)- for other bases, divide logarithms. As
logBase(81, 3)shows, the result can be slightly off, so round it if you expect an integer math.Log(0)is-Infand the logarithm of a negative number isNaN
math.Log1p(x) computes log(1 + x) and math.Expm1(x) computes exp(x) - 1. When x is close to zero, 1 + x loses most of the digits of x before the logarithm is even computed. In the example the naive version is off by 11%, while Log1p and Expm1 give the right answer.
Trigonometry
Trigonometric functions take and return angles in radians:
package main
import (
"fmt"
"math"
)
func deg2rad(d float64) float64 { return d * math.Pi / 180 }
func rad2deg(r float64) float64 { return r * 180 / math.Pi }
func main() {
fmt.Println(math.Sin(deg2rad(30)))
fmt.Println(math.Cos(deg2rad(60)))
fmt.Println(math.Sin(math.Pi))
fmt.Println(rad2deg(math.Asin(0.5)))
s, c := math.Sincos(deg2rad(45))
fmt.Printf("%.4f %.4f\n", s, c)
// Atan2 gets the quadrant right, Atan(y/x) doesn't
fmt.Println(rad2deg(math.Atan2(1, -1)))
fmt.Println(rad2deg(math.Atan(1 / -1.0)))
// rotate point (1, 0) by 90 degrees
x, y := 1.0, 0.0
a := deg2rad(90)
rx := x*math.Cos(a) - y*math.Sin(a)
ry := x*math.Sin(a) + y*math.Cos(a)
fmt.Printf("(%.3f, %.3f)\n", rx, ry)
}
0.49999999999999994
0.5000000000000001
1.2246467991473515e-16
30.000000000000004
0.7071 0.7071
135
-45
(0.000, 1.000)
Since math.Pi is not exactly π, math.Sin(math.Pi) is a tiny number instead of 0, and math.Sin(30°) is 0.49999999999999994. Format results with a fixed number of digits, or compare with a tolerance (see below).
math.Sincos returns both sine and cosine, which is faster than calling them separately.
Use math.Atan2(y, x) instead of math.Atan(y / x) to get the angle of a vector. Atan2 looks at the signs of both arguments and returns an angle in the correct quadrant, in the range [-π, π]. It also handles x == 0 without dividing by zero. Here the vector (-1, 1) points up-left at 135°, but Atan(-1) says -45°.
There are also the inverse functions Asin, Acos, Atan and the hyperbolic functions Sinh, Cosh, Tanh, Asinh, Acosh, Atanh.
Infinity, NaN and negative zero
Floating-point math in Go follows IEEE 754. Operations that have no meaningful result return special values instead of panicking:
package main
import (
"fmt"
"math"
)
func main() {
posInf := math.Inf(1)
negInf := math.Inf(-1)
nan := math.NaN()
fmt.Println(posInf, negInf, nan)
zero := 0.0
fmt.Println(1/zero, -1/zero, zero/zero)
fmt.Println(posInf-posInf, posInf*0)
fmt.Println(nan == nan, nan < 1, nan > 1)
fmt.Println(math.IsNaN(nan), math.IsInf(negInf, -1), math.IsInf(posInf, 0))
negZero := math.Copysign(0, -1)
fmt.Println(negZero, negZero == 0, math.Signbit(negZero))
big := math.MaxFloat64
fmt.Println(big * 2)
fmt.Println(math.Nextafter(1, 2))
fmt.Println(math.Float64bits(1.0) == 0x3FF0000000000000)
fmt.Printf("%#016x\n", math.Float64bits(-2.5))
}
+Inf -Inf NaN
+Inf -Inf NaN
NaN NaN
false false false
true true true
-0 true true
+Inf
1.0000000000000002
true
0xc004000000000000
Things to remember:
- floating-point division by zero gives
+Inf,-InforNaN. Only integer division by zero panics NaNis not equal to anything, including itself.x == math.NaN()is alwaysfalse, so usemath.IsNaN(x)math.IsInf(x, 1)checks for+Inf,math.IsInf(x, -1)for-Inf, andmath.IsInf(x, 0)for either-0equals0. Usemath.Signbitto tell them apart- overflowing
float64gives+Inf, it doesn't wrap around like integers math.Nextafter(x, y)returns the next representablefloat64afterxin the direction ofymath.Float64bitsandmath.Float64frombitsconvert between afloat64and its raw IEEE 754 bits
Because NaN isn't equal to itself, a NaN key in a map can never be looked up, and sorting a slice that contains NaN with sort.Float64s puts the NaN values first. slices.Sort does the same.
A NaN spreads through every calculation it touches, so one bad input can turn a whole report into NaN. Validate input with math.IsNaN and math.IsInf at the boundary of your program.
Comparing floats
Most decimal fractions like 0.1 can't be represented exactly in binary, so results of arithmetic are often a tiny bit off. Comparing floats with == is usually a bug:
package main
import (
"fmt"
"math"
)
func almostEqual(a, b, relTol, absTol float64) bool {
if a == b {
return true
}
diff := math.Abs(a - b)
return diff <= max(relTol*max(math.Abs(a), math.Abs(b)), absTol)
}
func main() {
x, y := 0.1, 0.2
a := x + y
fmt.Println(a, a == 0.3)
fmt.Println(almostEqual(a, 0.3, 1e-9, 0))
fmt.Println(almostEqual(1e20, 1e20+1e5, 1e-9, 0))
fmt.Println(almostEqual(1e-20, 0, 1e-9, 1e-12))
// summing many small values accumulates error
sum := 0.0
for range 10 {
sum += 0.1
}
fmt.Println(sum)
}
0.30000000000000004 false
true
true
true
0.9999999999999999
almostEqual uses a relative tolerance, which scales with the size of the numbers, and an absolute tolerance, which is needed when comparing against zero (a relative tolerance of anything compared to 0 is 0). This is the same approach as Python's math.isclose.
The right tolerance depends on your problem. 1e-9 is a reasonable default for values computed with a handful of operations.
Random numbers
Use package math/rand/v2, added in Go 1.22. The old math/rand still works, but the v2 API is better and its top-level functions are seeded automatically.
package main
import (
"fmt"
"math/rand/v2"
)
func main() {
fmt.Println(rand.IntN(100)) // [0, 100)
fmt.Println(rand.Float64()) // [0.0, 1.0)
fmt.Println(rand.N(10) + 1) // generic: [1, 10]
fmt.Println(rand.Int64N(1e12))
words := []string{"a", "b", "c", "d", "e"}
rand.Shuffle(len(words), func(i, j int) {
words[i], words[j] = words[j], words[i]
})
fmt.Println(words)
fmt.Println(rand.Perm(5))
// reproducible sequence with a fixed seed
r := rand.New(rand.NewPCG(1, 2))
fmt.Println(r.IntN(100), r.IntN(100), r.IntN(100))
r = rand.New(rand.NewPCG(1, 2))
fmt.Println(r.IntN(100), r.IntN(100), r.IntN(100))
// normally distributed: mean 170, stddev 10
fmt.Printf("%.1f\n", rand.NormFloat64()*10+170)
}
49
0.875763578070499
5
191380351680
[d b c e a]
[4 0 1 3 2]
76 61 78
76 61 78
177.5
Your output will differ, except for the two lines from the generator with a fixed seed.
rand.IntN(n)returns anintin[0, n). It panics ifn <= 0rand.N(n)is generic and works with any integer type, includingtime.Duration:rand.N(5 * time.Second)gives a random delayrand.Float64()returns a value in[0.0, 1.0)rand.Shuffleandrand.Permrandomly permute elementsrand.NormFloat64andrand.ExpFloat64produce normally and exponentially distributed values
The top-level functions are safe to use from multiple goroutines. A *rand.Rand created with rand.New is not, so either use it from a single goroutine or protect it with a mutex.
To get a reproducible sequence (for tests or simulations), create a generator with a fixed seed, e.g. rand.NewPCG(seed1, seed2). There's no global rand.Seed in v2.
math/rand/v2 is not suitable for passwords, tokens, or keys. Use crypto/rand for anything security-related. Since Go 1.24 rand.Text() from crypto/rand returns a random string you can use as a secret token.
Complex numbers
Go has built-in complex64 and complex128 types. The built-ins complex, real and imag create and take apart complex numbers, and the arithmetic operators work on them. Package math/cmplx has the math functions:
package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
c := complex(3, 4)
fmt.Println(c, real(c), imag(c))
fmt.Println(cmplx.Abs(c))
fmt.Println(cmplx.Sqrt(-1))
fmt.Println(cmplx.Exp(complex(0, math.Pi)))
r, theta := cmplx.Polar(c)
fmt.Printf("r=%.2f theta=%.4f\n", r, theta)
fmt.Println(cmplx.Rect(r, theta))
// roots of x^2 + 2x + 5 = 0
a, b, cc := 1.0, 2.0, 5.0
d := cmplx.Sqrt(complex(b*b-4*a*cc, 0))
x1 := (complex(-b, 0) + d) / complex(2*a, 0)
x2 := (complex(-b, 0) - d) / complex(2*a, 0)
fmt.Println(x1, x2)
}
(3+4i) 3 4
5
(0+1i)
(-1+1.2246467991473515e-16i)
r=5.00 theta=0.9273
(3.0000000000000004+3.9999999999999996i)
(-1+2i) (-1-2i)
cmplx.Exp(iπ) shows Euler's identity e^(iπ) = -1, with the usual tiny floating-point error in the imaginary part.
Example: basic statistics
Putting it together, here's how to compute the mean, the standard deviation, and the median of a slice of numbers:
package main
import (
"fmt"
"math"
"slices"
)
func stats(xs []float64) (mean, stddev, median float64) {
sum := 0.0
for _, x := range xs {
sum += x
}
mean = sum / float64(len(xs))
sq := 0.0
for _, x := range xs {
sq += (x - mean) * (x - mean)
}
stddev = math.Sqrt(sq / float64(len(xs)))
s := slices.Clone(xs)
slices.Sort(s)
n := len(s)
if n%2 == 1 {
median = s[n/2]
} else {
median = (s[n/2-1] + s[n/2]) / 2
}
return
}
func main() {
data := []float64{2, 4, 4, 4, 5, 5, 7, 9}
mean, sd, med := stats(data)
fmt.Printf("mean=%.2f stddev=%.2f median=%.2f\n", mean, sd, med)
fmt.Println(slices.Min(data), slices.Max(data))
}
mean=5.00 stddev=2.00 median=4.50
2 9
This computes the population standard deviation. For the sample standard deviation divide by len(xs) - 1 instead. For large data sets with values of very different magnitudes, a single-pass algorithm like Welford's is more numerically stable.
slices.Min and slices.Max return the smallest and largest elements of a slice. They panic on an empty slice.
Summary
mathworks onfloat64. Convert integers andfloat32values explicitly- use the built-in
minandmaxfor any ordered type math.Roundrounds halves away from zero,math.RoundToEvenrounds halves to even,int(x)truncates- round only when formatting output, and don't store money in floats
- write small helpers for integer
AbsandPowinstead of converting tofloat64 %andmath.Modkeep the sign of the dividend; use((a % n) + n) % nfor a non-negative modulo- float operations return
InfandNaNinstead of panicking; check withmath.IsInfandmath.IsNaN - compare floats with a tolerance, not
== - use
math/rand/v2for random numbers andcrypto/randfor secrets