The math module provides mathematical functions and constants. All functions are accessed via the math. prefix.
Constants
| Constant | Value | Description |
|---|
math.pi | 3.14159... | Ratio of circle circumference to diameter |
Functions
| Function | Arguments | Returns | Description |
|---|
math.sqrt(x) | number | float | Square root of x |
math.pow(base, exp) | base, exponent | float | Base raised to exponent power |
math.abs(x) | number | number | Absolute value |
math.sin(x) | radians | float | Sine of angle |
math.cos(x) | radians | float | Cosine of angle |
math.tan(x) | radians | float | Tangent of angle |
math.floor(x) | number | float | Round down to nearest integer |
math.ceil(x) | number | float | Round up to nearest integer |
math.round(x) | number | number | Round to nearest integer |
math.min(a, b, ...) | 2+ numbers | number | Smallest value |
math.max(a, b, ...) | 2+ numbers | number | Largest value |
math.random() | none | float | Random number 0.0 to 1.0 |
math.random(max) | int max | int | Random int 0 to max-1 |
math.random(min, max) | int min, int max | int | Random int min to max (inclusive) |
Examples
Basic calculations
class App {
print(math.sqrt(16)); // 4.0
print(math.pow(2, 10)); // 1024.0
print(math.abs(-42)); // 42
print(math.pi * 2); // 6.283185...
}
Trigonometry
class App {
const PI = math.pi;
print(math.sin(PI / 2)); // 1.0 (90 degrees)
print(math.cos(PI)); // -1.0 (180 degrees)
print(math.tan(0)); // 0.0
}
Rounding
class App {
print(math.floor(3.7)); // 3.0
print(math.ceil(3.2)); // 4.0
print(math.round(3.5)); // 4
}
Min / Max
class App {
print(math.min(10, 5)); // 5
print(math.max(10, 5)); // 10
print(math.min(3, 1, 4, 1, 5)); // 1
print(math.max(3, 1, 4, 1, 5)); // 5
}
Random numbers
class App {
// Random float 0.0 to 1.0
print(math.random()); // e.g., 0.8473...
// Random int 0 to 99
print(math.random(100)); // e.g., 42
// Random int 1 to 6 (dice roll)
print(math.random(1, 6)); // e.g., 4
}
Complete example: Dice roller
class DiceRoller {
const SIDES = 6;
const ROLLS = 5;
fn rollDice() {
print("Rolling", ROLLS, "d", SIDES, "dice:");
@unsafe for (let i = 0; i < ROLLS; i = i + 1) {
let roll = math.random(1, SIDES);
print("Roll", i + 1, ":", roll);
}
}
rollDice();
}
Error handling
math.sqrt() of a negative number throws an errormath.random(max) requires max > 0math.random(min, max) requires max > min- All math functions require numeric arguments