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
| Constant | Value | Description |
|---|---|---|
Math.PI | 3.141592653589793 | Ratio of a circle’s circumference to its diameter. |
Math.E | 2.718281828459045 | Euler’s number, the base of natural logarithms. |
Math.LN2 | 0.6931471805599453 | Natural log of 2. |
Math.LN10 | 2.302585092994046 | Natural log of 10. |
Math.LOG2E | 1.4426950408889634 | Base-2 log of E. |
Math.LOG10E | 0.4342944819032518 | Base-10 log of E. |
Math.SQRT2 | 1.4142135623730951 | Square root of 2. |
Math.SQRT1_2 | 0.7071067811865476 | Square root of ½. |
if (Math.PI > 3.14 && Math.PI < 3.15) { console.log("PI looks right");}Rounding
Math.floor(x: f64): f64 // largest integer <= xMath.ceil(x: f64): f64 // smallest integer >= xMath.round(x: f64): f64 // nearest integer, halves away from zeroMath.trunc(x: f64): f64 // drops the fractional partMath.floor(3.7); // 3.0Math.ceil(3.2); // 4.0Math.round(3.5); // 4.0Math.trunc(3.9); // 3.0Powers, roots, and logarithms
Math.pow(x: f64, y: f64): f64 // x raised to the power yMath.sqrt(x: f64): f64 // square rootMath.cbrt(x: f64): f64 // cube rootMath.exp(x: f64): f64 // e raised to the power xMath.log(x: f64): f64 // natural logarithm (base e)Math.log2(x: f64): f64 // base-2 logarithmMath.log10(x: f64): f64 // base-10 logarithmMath.pow(2.0, 10.0); // 1024.0Math.sqrt(144.0); // 12.0Math.log2(8.0); // 3.0Trigonometry
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): f64Math.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): f64Math.asinh(x: f64): f64 Math.acosh(x: f64): f64 Math.atanh(x: f64): f64Math.sin(0.0); // 0.0Math.cos(0.0); // 1.0Math.cos(Math.PI); // -1.0Math.atan2(1.0, 1.0); // 0.7853... (π/4)Bit & precision helpers
Math.log1p(x: f64): f64 // log(1 + x), accurate near 0Math.expm1(x: f64): f64 // exp(x) - 1, accurate near 0Math.fround(x: f64): f64 // round to the nearest 32-bit floatMath.clz32(x: f64): f64 // leading-zero count of x as a uint32Math.imul(a: f64, b: f64): f64 // 32-bit integer multiplicationSign, absolute value, and comparison
Math.abs(x: f64): f64 // absolute valueMath.sign(x: f64): f64 // -1.0, 0.0, or 1.0Math.min(a: f64, b: f64): f64 // smaller of a and bMath.max(a: f64, b: f64): f64 // larger of a and bMath.hypot(a: f64, b: f64): f64 // sqrt(a*a + b*b)Math.abs(-5.0); // 5.0Math.sign(-3.0); // -1.0Math.max(2.0, 9.0); // 9.0Math.hypot(3.0, 4.0); // 5.0Random
Math.random() returns a uniformly distributed f64 in the range [0.0, 1.0).
let r: f64 = Math.random(); // e.g. 0.4271...