Standard Library - Math Functions

Basic mathematical functions in Romasm

Overview

The Romasm standard library provides pre-built mathematical functions that you can call from your programs. These functions are located in stdlib/math.romasm and are automatically linked when you use the linker system.

Note: All functions use fixed-point arithmetic. Numbers are scaled (typically by 100 or 1000) to represent decimals as integers.

Available Functions

factorial

Calculates the factorial of a number: n! = n × (n-1) × ... × 2 × 1

CALL factorial
Input Output
R0 = n (integer) R0 = n! (factorial)
Example:
LOAD R0, 5
CALL factorial
PRINT R0    ; Outputs 120 (5! = 5×4×3×2×1)

power

Calculates base raised to the power of exponent: base^exponent

CALL power
Input Output
R0 = base
R1 = exponent
R0 = base^exponent
Example:
LOAD R0, 2      ; base = 2
LOAD R1, 8      ; exponent = 8
CALL power
PRINT R0        ; Outputs 256 (2^8)

sqrt

Calculates the square root using Newton's method

CALL sqrt
Input Output
R0 = n (scaled by 1000) R0 = √n (scaled by 1000)
Example:
LOAD R0, 25000  ; n = 25.000 (scaled by 1000)
CALL sqrt
PRINT R0        ; Outputs ~5000 (5.000 = √25)

Algorithm: Uses Newton's method: x_{n+1} = (x_n + n/x_n) / 2

arg_reduce

Reduces an angle to a manageable range (typically -90° to 90°) for trigonometric calculations

CALL arg_reduce
Input Output
R0 = angle (in degrees) R0 = reduced angle (in degrees)

Purpose: Ensures fast convergence of Taylor series and numerical stability for trigonometric functions.

Using Standard Library Functions

To use these functions in your Romasm code, you need to:

  1. Ensure the linker is enabled (automatic in the calculator, manual in IDE)
  2. Load your input values into the appropriate registers
  3. Call the function using CALL function_name
  4. Read the result from the output register (usually R0)

Complete Example

; Calculate 3^4 and then take the square root
LOAD R0, 3      ; base = 3
LOAD R1, 4      ; exponent = 4
CALL power      ; R0 = 3^4 = 81

; Now calculate sqrt(81)
; sqrt expects input scaled by 1000
LOAD R1, 1000
MUL R0, R1      ; R0 = 81000 (81.000 scaled)
CALL sqrt       ; R0 = ~9000 (9.000 = √81)
PRINT R0

Fixed-Point Scaling

Romasm uses fixed-point arithmetic. Here's how scaling works:

  • Scale by 100: 3050 represents 30.50
  • Scale by 1000: 30500 represents 30.500

When calling functions like sqrt, make sure your input is properly scaled. The function will return a result with the same scaling.

Related Documentation