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. |
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.sin(0.0); // 0.0Math.cos(0.0); // 1.0Math.cos(Math.PI); // -1.0Sign, 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...