Mojo Math Module
The math module provides mathematical functions and constants that go beyond basic arithmetic. Square roots, trigonometric functions, logarithms, rounding, and fundamental constants like π and e all live here. These tools appear in physics simulations, graphics, signal processing, finance, and machine learning — anywhere numbers describe the real world.
Importing the Math Module
from math import (
sqrt, cbrt, pow,
sin, cos, tan, asin, acos, atan, atan2,
exp, log, log2, log10,
floor, ceil, round, abs,
pi, e, tau, inf, nan,
isnan, isinf, isfinite,
hypot, factorial,
)
Constants
from math import pi, e, tau, inf, nan
fn main():
print(pi) # 3.141592653589793 — ratio of circumference to diameter
print(e) # 2.718281828459045 — base of natural logarithm
print(tau) # 6.283185307179586 — 2π, full circle in radians
print(inf) # inf — positive infinity
print(nan) # nan — Not a Number
What these constants mean: π (pi) = 3.14159... circle circumference ÷ diameter e = 2.71828... growth base, appears in compound interest and ML τ (tau) = 2π = 6.28... full rotation in radians inf = ∞ larger than any finite number nan = undefined result of 0/0, sqrt(-1), etc.
Power and Root Functions
from math import sqrt, cbrt, pow
fn main():
print(sqrt(25.0)) # 5.0 — square root
print(sqrt(2.0)) # 1.4142135623...
print(cbrt(27.0)) # 3.0 — cube root
print(pow(2.0, 10.0)) # 1024.0 — 2 to the power 10
print(pow(9.0, 0.5)) # 3.0 — same as sqrt(9)
Root functions: sqrt(x) = x^(1/2) → finds number that, squared, gives x cbrt(x) = x^(1/3) → finds number that, cubed, gives x sqrt(16) = 4 because 4×4 = 16 cbrt(8) = 2 because 2×2×2 = 8
Trigonometric Functions
Mojo's trig functions work in radians, not degrees. One full circle = 2π radians = 360 degrees.
from math import sin, cos, tan, pi
fn deg_to_rad(degrees: Float64) -> Float64:
return degrees * pi / 180.0
fn main():
print(sin(0.0)) # 0.0
print(sin(pi / 2.0)) # 1.0 — sin(90°)
print(cos(0.0)) # 1.0
print(cos(pi)) # -1.0 — cos(180°)
print(tan(pi / 4.0)) # 1.0 — tan(45°)
# Convert degrees first
print(sin(deg_to_rad(30.0))) # 0.5
print(cos(deg_to_rad(60.0))) # 0.5
Unit circle diagram:
sin=1
│
cos=-1 ───┼─── cos=1
│
sin=-1
Angle 0° (0 rad): sin=0, cos=1
Angle 90° (π/2 rad): sin=1, cos=0
Angle 180° (π rad): sin=0, cos=-1
Angle 270° (3π/2): sin=-1, cos=0
Inverse Trig Functions
from math import asin, acos, atan, atan2, pi
fn rad_to_deg(r: Float64) -> Float64:
return r * 180.0 / pi
fn main():
print(rad_to_deg(asin(1.0))) # 90.0 — angle whose sin is 1
print(rad_to_deg(acos(0.5))) # 60.0 — angle whose cos is 0.5
print(rad_to_deg(atan(1.0))) # 45.0 — angle whose tan is 1
print(rad_to_deg(atan2(1.0, 1.0))) # 45.0 — atan of y/x with quadrant
Exponential and Logarithm Functions
from math import exp, log, log2, log10
fn main():
print(exp(1.0)) # 2.718... — e^1
print(exp(2.0)) # 7.389... — e^2
print(log(1.0)) # 0.0 — natural log (base e)
print(log(e)) # 1.0
print(log2(8.0)) # 3.0 — log base 2: 2^3 = 8
print(log10(1000.0)) # 3.0 — log base 10: 10^3 = 1000
Exp vs Log (inverse pair):
exp(x) → "raise e to the power x" e^3 = 20.09
log(x) → "what power of e gives x" log(20.09) ≈ 3
They undo each other:
log(exp(5)) = 5
exp(log(5)) = 5
Rounding Functions
from math import floor, ceil, round
fn main():
var x = 3.7
var y = -2.3
print(floor(x)) # 3.0 — round DOWN (toward -∞)
print(floor(y)) # -3.0 — round DOWN
print(ceil(x)) # 4.0 — round UP (toward +∞)
print(ceil(y)) # -2.0 — round UP
print(round(x)) # 4.0 — round to nearest integer
print(round(y)) # -2.0 — round to nearest integer
# Round to N decimal places
print(round(3.14159, 2)) # 3.14
print(round(2.71828, 3)) # 2.718
Rounding comparison: Value: 3.7 -2.3 floor: 3.0 -3.0 (always goes toward -∞) ceil: 4.0 -2.0 (always goes toward +∞) round: 4.0 -2.0 (goes to nearest, .5 rounds to even) Int(): 3 -2 (truncates toward zero, not round)
Absolute Value and Hypotenuse
from math import abs, hypot
fn main():
print(abs(-7.5)) # 7.5 — removes the sign
print(abs(3.0)) # 3.0
# Hypotenuse of a right triangle: sqrt(a² + b²)
print(hypot(3.0, 4.0)) # 5.0 — the classic 3-4-5 triangle
print(hypot(5.0, 12.0)) # 13.0 — 5-12-13 triangle
Checking Special Float Values
from math import isnan, isinf, isfinite, nan, inf, sqrt
fn main():
var bad = nan
var huge = inf
var normal = 42.0
print(isnan(bad)) # True
print(isinf(huge)) # True
print(isfinite(normal)) # True
print(isfinite(huge)) # False
# Operations that produce special values:
var zero_div = 1.0 / 0.0 # inf
var neg_sqrt = sqrt(-1.0) # nan (on some platforms)
var inf_minus = inf - inf # nan
print(isinf(zero_div)) # True
Practical Example: Distance Between Two GPS Points
from math import sin, cos, asin, sqrt, pi
fn haversine(lat1: Float64, lon1: Float64,
lat2: Float64, lon2: Float64) -> Float64:
let R = 6371.0 # Earth radius in km
let to_rad = pi / 180.0
var dlat = (lat2 - lat1) * to_rad
var dlon = (lon2 - lon1) * to_rad
var a = sin(dlat/2)**2 + cos(lat1*to_rad)*cos(lat2*to_rad)*sin(dlon/2)**2
var c = 2.0 * asin(sqrt(a))
return R * c
fn main():
# Distance from New Delhi to Mumbai
var dist = haversine(28.6139, 77.2090, 19.0760, 72.8777)
print("Distance:", dist, "km") # ≈ 1153 km
Key Takeaways
Import specific functions from math to avoid namespace clutter. Use pi, e, and tau as constants rather than typing approximations. Trig functions take radians — multiply degrees by pi/180 to convert. exp and log are inverse operations; log2 and log10 give logarithms in other bases. Use floor, ceil, and round for controlled rounding — they behave differently for negative numbers. Check for nan and inf with isnan, isinf, and isfinite before using float results from division or roots.
