Math Module

The math module provides mathematical functions and constants. All functions are accessed via the math. prefix.

Constants

ConstantValueDescription
math.pi3.14159...Ratio of circle circumference to diameter

Functions

FunctionArgumentsReturnsDescription
math.sqrt(x)numberfloatSquare root of x
math.pow(base, exp)base, exponentfloatBase raised to exponent power
math.abs(x)numbernumberAbsolute value
math.sin(x)radiansfloatSine of angle
math.cos(x)radiansfloatCosine of angle
math.tan(x)radiansfloatTangent of angle
math.floor(x)numberfloatRound down to nearest integer
math.ceil(x)numberfloatRound up to nearest integer
math.round(x)numbernumberRound to nearest integer
math.min(a, b, ...)2+ numbersnumberSmallest value
math.max(a, b, ...)2+ numbersnumberLargest value
math.random()nonefloatRandom number 0.0 to 1.0
math.random(max)int maxintRandom int 0 to max-1
math.random(min, max)int min, int maxintRandom 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 error
  • math.random(max) requires max > 0
  • math.random(min, max) requires max > min
  • All math functions require numeric arguments