Skip to content

Math

The global Math object is available in every program without an import, just like console. It exposes the constants and floating-point functions you know from JavaScript. Every method operates on f64.

console.log("The square root of 16 is 4");
if (Math.sqrt(16.0) == 4.0) {
console.log("correct!");
}

Constants

ConstantValueDescription
Math.PI3.141592653589793Ratio of a circle’s circumference to its diameter.
Math.E2.718281828459045Euler’s number, the base of natural logarithms.
Math.LN20.6931471805599453Natural log of 2.
Math.LN102.302585092994046Natural log of 10.
Math.LOG2E1.4426950408889634Base-2 log of E.
Math.LOG10E0.4342944819032518Base-10 log of E.
Math.SQRT21.4142135623730951Square root of 2.
Math.SQRT1_20.7071067811865476Square root of ½.
if (Math.PI > 3.14 && Math.PI < 3.15) {
console.log("PI looks right");
}

Rounding

Math.floor(x: f64): f64 // largest integer <= x
Math.ceil(x: f64): f64 // smallest integer >= x
Math.round(x: f64): f64 // nearest integer, halves away from zero
Math.trunc(x: f64): f64 // drops the fractional part
Math.floor(3.7); // 3.0
Math.ceil(3.2); // 4.0
Math.round(3.5); // 4.0
Math.trunc(3.9); // 3.0

Powers, roots, and logarithms

Math.pow(x: f64, y: f64): f64 // x raised to the power y
Math.sqrt(x: f64): f64 // square root
Math.cbrt(x: f64): f64 // cube root
Math.exp(x: f64): f64 // e raised to the power x
Math.log(x: f64): f64 // natural logarithm (base e)
Math.log2(x: f64): f64 // base-2 logarithm
Math.log10(x: f64): f64 // base-10 logarithm
Math.pow(2.0, 10.0); // 1024.0
Math.sqrt(144.0); // 12.0
Math.log2(8.0); // 3.0

Trigonometry

Math.sin(x: f64): f64 // sine of x (radians)
Math.cos(x: f64): f64 // cosine of x (radians)
Math.tan(x: f64): f64 // tangent of x (radians)
Math.asin(x: f64): f64 Math.acos(x: f64): f64 Math.atan(x: f64): f64
Math.atan2(y: f64, x: f64): f64 // angle of the point (x, y)
Math.sinh(x: f64): f64 Math.cosh(x: f64): f64 Math.tanh(x: f64): f64
Math.asinh(x: f64): f64 Math.acosh(x: f64): f64 Math.atanh(x: f64): f64
Math.sin(0.0); // 0.0
Math.cos(0.0); // 1.0
Math.cos(Math.PI); // -1.0
Math.atan2(1.0, 1.0); // 0.7853... (π/4)

Bit & precision helpers

Math.log1p(x: f64): f64 // log(1 + x), accurate near 0
Math.expm1(x: f64): f64 // exp(x) - 1, accurate near 0
Math.fround(x: f64): f64 // round to the nearest 32-bit float
Math.clz32(x: f64): f64 // leading-zero count of x as a uint32
Math.imul(a: f64, b: f64): f64 // 32-bit integer multiplication

Sign, absolute value, and comparison

Math.abs(x: f64): f64 // absolute value
Math.sign(x: f64): f64 // -1.0, 0.0, or 1.0
Math.min(a: f64, b: f64): f64 // smaller of a and b
Math.max(a: f64, b: f64): f64 // larger of a and b
Math.hypot(a: f64, b: f64): f64 // sqrt(a*a + b*b)
Math.abs(-5.0); // 5.0
Math.sign(-3.0); // -1.0
Math.max(2.0, 9.0); // 9.0
Math.hypot(3.0, 4.0); // 5.0

Random

Math.random() returns a uniformly distributed f64 in the range [0.0, 1.0).

let r: f64 = Math.random(); // e.g. 0.4271...