Math
Math holds numeric functions and constants. The functions over float64 follow IEEE 754 and never panic: Math.log(0.0) is -Infinity, and Math.sqrt(-1.0) is NaN.
Details
- Most functions take and return
float64only. Numeric types never mix, so anintargument is a compile error: convert it withfloat64(n).Math.abs,Math.min,Math.max, andMath.clampare generic and keep their argument's type. - The
float64functions follow IEEE 754 and never panic: outside its domain a function returnsNaNor an infinity, asMath.sqrt(-1.0)isNaNandMath.log(0.0)is-Infinity. Three functions do panic:Math.abson the most negative value of an integer type,Math.clampwhenlo > hior a bound isNaN, andMath.randomIntwhento <= from. NaNis not equal to anything, itself included. Test for it with Math.isNaN.- Angles are in radians.
- Math.random and Math.randomInt cannot be seeded. Use Random for numbers you can repeat, and Crypto.randomBytes for keys and tokens.
Basic examples
Call a function through the namespace:
Math.sqrt(2.0) // 1.4142135623730951
Math.pow(2.0, 10.0) // 1024.0
Math.abs(-3) // 3
Math.max(2, 7) // 7Round a float64 four ways:
Math.floor(-2.5) // -3.0
Math.ceil(-2.5) // -2.0
Math.round(-2.5) // -3.0
Math.trunc(-2.5) // -2.0The constants are values of the namespace:
Math.PI // 3.141592653589793
Math.E // 2.718281828459045
Math.maxInt // 9223372036854775807Scope
Math.abs, Math.min, Math.max, and Math.clamp take any one numeric type, and the result has it:
Math.abs(-2.5) // 2.5
Math.abs(int8(-5)) // 5
Math.clamp(15, 0, 10) // 10Math.min, Math.max, and Math.clamp also take strings, which they compare as < does:
Math.min("pear", "apple") // "apple"
Math.clamp("m", "a", "f") // "f"An int goes through float64 on its way into a float64 function, and through Math.toInt or int on its way back:
let total = 7
let parts = 3
Math.ceil(float64(total) / float64(parts)) // 3.0
Math.toInt(Math.ceil(float64(total) / float64(parts))) // 3
int(Math.trunc(-2.7)) // -2Results outside a function's domain are NaN or an infinity:
Math.sqrt(-1.0) // NaN
Math.log(0.0) // -Infinity
Math.exp(1000.0) // Infinity
Math.maxFloat64 * 2.0 // Infinity
Math.Infinity - Math.Infinity // NaNMath.random is uniform in [0, 1) and cannot be seeded:
let r = Math.random()
r >= 0.0 && r < 1.0 // trueCalls chain through a pipe:
16.0 | Math.sqrt() | Math.log2() // 2.0Functions by job
Sign, size, and bounds
- Math.abs: the absolute value of any number
- Math.min, Math.max: the smaller or larger of two numbers or strings
- Math.clamp: a value held within
lo ..= hi
Rounding
- Math.floor: the greatest whole number not above
x - Math.ceil: the least whole number not below
x - Math.round: the nearest whole number, halves away from zero
- Math.trunc:
xwith its fraction dropped, toward zero - Math.toInt: a whole
float64as anint, ornull
Powers, roots, and logarithms
- Math.pow:
xraised to the powery - Math.sqrt, Math.cbrt: the square and cube root
- Math.hypot: the square root of
x² + y², without overflow in between - Math.exp:
eraised to the powerx - Math.log, Math.log2, Math.log10: the natural, base-2, and base-10 logarithm
Trigonometry
- Math.sin, Math.cos, Math.tan: the sine, cosine, and tangent of an angle in radians
- Math.asin, Math.acos, Math.atan: the inverse functions, in radians
- Math.atan2: the angle of the point
(x, y), from-PItoPI
Testing floats
- Math.isNaN: whether
xisNaN - Math.isFinite: whether
xis neitherNaNnor an infinity
Random numbers
- Math.random: a uniformly random
float64in[0, 1) - Math.randomInt: a uniformly random
intfromfrom, inclusive, toto, exclusive
Constants
| Constant | Type | Value |
|---|---|---|
Math.PI | float64 | π, 3.141592653589793 |
Math.E | float64 | e, 2.718281828459045 |
Math.NaN | float64 | not-a-number |
Math.Infinity | float64 | positive infinity; -Math.Infinity is negative |
Math.maxFloat64 | float64 | the largest finite float64 |
Math.minInt | int | -2^63, which no literal writes |
Math.maxInt | int | 2^63 - 1 |
Math.maxUint64 | uint64 | 2^64 - 1, which no literal writes |
Type bounds
- Number: any integer or floating-point type
- Integer: any integer type
- Ordered: any number type or
string, the types<compares
Applications
Convert degrees to radians before a trigonometric call:
func radians(degrees: float64): float64 {
degrees * Math.PI / 180.0
}
Math.sin(radians(90.0)) // 1.0Measure the distance between two points:
type Point = { x: float64, y: float64 }
func distance(a: Point, b: Point): float64 {
Math.hypot(b.x - a.x, b.y - a.y)
}
distance(Point{ x: 1.0, y: 1.0 }, Point{ x: 4.0, y: 5.0 }) // 5.0Round to two decimal places:
let x = 3.14159
Math.round(x * 100.0) / 100.0 // 3.14Grow a deposit by compound interest:
let deposit = 1000.0
let rate = 0.05
deposit * Math.pow(1.0 + rate, 10.0) // 1628.8946267774415Keep a percentage within range:
let percents = [-12, 40, 130]
percents.map({ Math.clamp(x, 0, 100) }) // [0, 40, 100]Properties and relations
Math.floor and Math.ceil bracket x, and Math.trunc is one of them by sign:
for x in [2.5, -2.5, 3.0] {
assert(Math.floor(x) <= x && x <= Math.ceil(x))
assert(Math.trunc(x) == (if x < 0.0 { Math.ceil(x) } else { Math.floor(x) }))
}Math.clamp is Math.max then Math.min:
for x in [-5, 3, 99] {
assert(Math.clamp(x, 0, 10) == Math.min(Math.max(x, 0), 10))
}Outside its domain a function gives NaN or an infinity, never a panic:
assert(Math.isNaN(Math.sqrt(-1.0)))
assert(Math.log(0.0) == -Math.Infinity)Possible issues
An int literal is not a float64. Write 2.0, or convert a variable with float64:
let n = 2
Math.sqrt(n) // error: cannot use int where float64 is expectedThe two arguments of Math.max must share one type:
Math.max(2, 3.5) // error: cannot use float64 where int is expectedNaN is not equal to itself, so == never finds it:
let x = Math.sqrt(-1.0)
x == Math.NaN // false
Math.isNaN(x) // trueMath.minInt has no absolute value in an int:
Math.abs(Math.minInt) // panic: Math.abs: integer overflowThe integer constants are limits, so arithmetic past them panics:
Math.maxInt + 1 // panic: integer overflowMath.clamp with the bounds swapped panics:
Math.clamp(5, 10, 0) // panic: Math.clamp needs lo <= hi, got 10 and 0See also
- Bits: bitwise operations and wrapping arithmetic on integers
- Random: a seeded generator of repeatable random numbers
- String.toFloat, String.fromFloat: numbers to and from text
- Array.sum, Array.min, Array.max: the same jobs over an array
