Skip to main content

Overview

The std.math module provides mathematical constants, functions, and utilities for numeric operations including trigonometry, logarithms, comparison, and bit manipulation.

Mathematical Constants

pub const e = 2.71828182845904523536028747135266249775724709369995;
pub const pi = 3.14159265358979323846264338327950288419716939937510;
pub const phi = 1.6180339887498948482045868343656381177203091798057628621;  // Golden ratio
pub const tau = 2 * pi;  // Circle constant

pub const log2e = 1.442695040888963407359924681001892137;
pub const log10e = 0.434294481903251827651128918916605082;
pub const ln2 = 0.693147180559945309417232121458176568;
pub const ln10 = 2.302585092994045684017991454684364208;

pub const sqrt2 = 1.414213562373095048801688724209698079;
pub const sqrt1_2 = 0.707106781186547524400844362104849039;

pub const rad_per_deg = 0.01745329251994329576923690768488612713;
pub const deg_per_rad = 57.29577951308232087679815481410517033;

Trigonometric Functions

sin, cos, tan

pub inline fn sin(value: anytype) @TypeOf(value);
pub inline fn cos(value: anytype) @TypeOf(value);
pub inline fn tan(value: anytype) @TypeOf(value);
Basic trigonometric functions. Use hardware instructions when available. Example:
const angle = std.math.pi / 4.0;
const sine = std.math.sin(angle);      // 0.707...
const cosine = std.math.cos(angle);    // 0.707...
const tangent = std.math.tan(angle);   // 1.0

asin, acos, atan, atan2

pub fn asin(x: anytype) @TypeOf(x);
pub fn acos(x: anytype) @TypeOf(x);
pub fn atan(x: anytype) @TypeOf(x);
pub fn atan2(y: anytype, x: anytype) @TypeOf(y, x);
Inverse trigonometric functions. Example:
const angle = std.math.asin(0.5);  // pi/6
const angle2 = std.math.atan2(1.0, 1.0);  // pi/4

Hyperbolic Functions

pub fn sinh(x: anytype) @TypeOf(x);
pub fn cosh(x: anytype) @TypeOf(x);
pub fn tanh(x: anytype) @TypeOf(x);

pub fn asinh(x: anytype) @TypeOf(x);
pub fn acosh(x: anytype) @TypeOf(x);
pub fn atanh(x: anytype) @TypeOf(x);

Angle Conversion

pub fn degreesToRadians(ang: anytype) @TypeOf(ang);
pub fn radiansToDegrees(ang: anytype) @TypeOf(ang);
Example:
const radians = std.math.degreesToRadians(90.0);  // pi/2
const degrees = std.math.radiansToDegrees(std.math.pi);  // 180.0

Exponential and Logarithmic Functions

exp, exp2

pub inline fn exp(value: anytype) @TypeOf(value);   // e^x
pub inline fn exp2(value: anytype) @TypeOf(value);  // 2^x
pub fn expm1(x: anytype) @TypeOf(x);                // e^x - 1

log, log2, log10

pub fn log(x: anytype) @TypeOf(x);    // Natural logarithm (ln)
pub fn log2(x: anytype) @TypeOf(x);   // Base-2 logarithm
pub fn log10(x: anytype) @TypeOf(x);  // Base-10 logarithm
pub fn log1p(x: anytype) @TypeOf(x);  // ln(1 + x)

pub fn log_int(comptime T: type, base: T, x: T) T;  // Integer logarithm
pub fn log10_int(x: anytype) @TypeOf(x);             // Integer log10
Example:
const natural = std.math.log(std.math.e);  // 1.0
const base2 = std.math.log2(8.0);          // 3.0
const base10 = std.math.log10(1000.0);     // 3.0

const int_log = std.math.log_int(u32, 2, 16);  // 4

pow, powi

pub fn pow(comptime T: type, x: T, y: T) T;      // x^y (float exponent)
pub fn powi(comptime T: type, x: T, y: T) T;     // x^y (integer exponent)
Example:
const result = std.math.pow(f64, 2.0, 3.0);  // 8.0
const int_result = std.math.powi(i32, 2, 10);  // 1024

Root Functions

pub fn sqrt(value: anytype) @TypeOf(value);   // Square root
pub fn cbrt(x: anytype) @TypeOf(x);           // Cube root
pub fn hypot(x: anytype, y: anytype) @TypeOf(x, y);  // sqrt(x^2 + y^2)
Example:
const sq = std.math.sqrt(16.0);     // 4.0
const cb = std.math.cbrt(27.0);     // 3.0
const hyp = std.math.hypot(3.0, 4.0);  // 5.0

Rounding Functions

pub inline fn round(value: anytype) @TypeOf(value);  // Round to nearest integer
pub inline fn floor(value: anytype) @TypeOf(value);  // Round down
pub inline fn ceil(value: anytype) @TypeOf(value);   // Round up
pub inline fn trunc(value: anytype) @TypeOf(value);  // Round toward zero
Example:
const r = std.math.round(3.7);   // 4.0
const f = std.math.floor(3.7);   // 3.0
const c = std.math.ceil(3.2);    // 4.0
const t = std.math.trunc(-3.7);  // -3.0

Floating Point Functions

Float Properties

pub fn floatMin(comptime T: type) T;        // Smallest normal value
pub fn floatMax(comptime T: type) T;        // Largest finite value
pub fn floatTrueMin(comptime T: type) T;    // Smallest subnormal value
pub fn floatEps(comptime T: type) T;        // Machine epsilon

pub fn inf(comptime T: type) T;             // Positive infinity
pub fn nan(comptime T: type) T;             // NaN (quiet)
pub fn snan(comptime T: type) T;            // NaN (signaling)

Float Classification

pub fn isNan(x: anytype) bool;
pub fn isSignalNan(x: anytype) bool;
pub fn isInf(x: anytype) bool;
pub fn isPositiveInf(x: anytype) bool;
pub fn isNegativeInf(x: anytype) bool;
pub fn isFinite(x: anytype) bool;
pub fn isNormal(x: anytype) bool;
pub fn signbit(x: anytype) bool;
Example:
const x = 1.0 / 0.0;  // inf
if (std.math.isInf(x)) {
    // x is infinite
}

const y = std.math.sqrt(-1.0);  // NaN
if (std.math.isNan(y)) {
    // y is not a number
}

Float Manipulation

pub fn copysign(x: anytype, y: anytype) @TypeOf(x, y);  // Magnitude of x, sign of y
pub fn scalbn(x: anytype, n: i32) @TypeOf(x);           // x * 2^n
pub fn ldexp(x: anytype, exp: i32) @TypeOf(x);          // x * 2^exp
pub fn frexp(x: anytype) Frexp(@TypeOf(x));             // Decompose to mantissa and exponent
pub fn modf(x: anytype) Modf(@TypeOf(x));               // Split into integer and fractional parts
Example:
const result = std.math.frexp(8.0);
// result.significand = 0.5, result.exponent = 4  (0.5 * 2^4 = 8)

const parts = std.math.modf(3.14);
// parts.ipart = 3.0, parts.fpart = 0.14

Comparison Functions

approxEqAbs

pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool;
Compares floating point values with absolute tolerance. Good for values near zero. Example:
const a = 0.1 + 0.2;
const b = 0.3;
if (std.math.approxEqAbs(f64, a, b, 1e-10)) {
    // a and b are approximately equal
}

approxEqRel

pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool;
Compares with relative tolerance. Better for larger values.

Clamping and Wrapping

clamp

pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper);
Limits a value to an inclusive range. Example:
const clamped = std.math.clamp(150, 0, 100);  // 100
const in_range = std.math.clamp(50, 0, 100);   // 50

wrap

pub fn wrap(x: anytype, r: anytype) @TypeOf(x);
Wraps a value to the half-open interval [-r, r). Example:
const angle = std.math.wrap(270, 180);  // -90 (wraps 270 to [-180, 180))

Integer Operations

Overflow-Checked Arithmetic

pub fn add(comptime T: type, a: T, b: T) !T;   // a + b
pub fn sub(comptime T: type, a: T, b: T) !T;   // a - b  
pub fn mul(comptime T: type, a: T, b: T) !T;   // a * b
pub fn negate(x: anytype) !@TypeOf(x);         // -x
Example:
const result = try std.math.add(u8, 200, 100);  // Error: overflow
const valid = try std.math.mul(i32, 100, 50);   // 5000

Division

pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T;  // Truncate toward zero
pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T;  // Round toward -inf
pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T;   // Round toward +inf
pub fn divExact(comptime T: type, numerator: T, denominator: T) !T;  // Error if remainder

pub fn mod(comptime T: type, numerator: T, denominator: T) !T;  // Modulo (always positive)
pub fn rem(comptime T: type, numerator: T, denominator: T) !T;  // Remainder (can be negative)
Example:
const q1 = try std.math.divTrunc(i32, -7, 3);   // -2
const q2 = try std.math.divFloor(i32, -7, 3);   // -3
const q3 = try std.math.divCeil(i32, 7, 3);     // 3

const m = try std.math.mod(i32, -7, 3);   // 2 (always >= 0)
const r = try std.math.rem(i32, -7, 3);   // -1 (can be < 0)

Bit Operations

pub fn shl(comptime T: type, a: T, shift_amt: anytype) T;    // Shift left
pub fn shr(comptime T: type, a: T, shift_amt: anytype) T;    // Shift right
pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T;  // Error on overflow

pub fn rotl(comptime T: type, x: T, r: anytype) T;  // Rotate left
pub fn rotr(comptime T: type, x: T, r: anytype) T;  // Rotate right
Example:
const shifted = std.math.shl(u8, 0b0001, 3);    // 0b1000 (8)
const rotated = std.math.rotl(u8, 0b1001, 1);   // 0b0011 (shifts wrap)

Power of Two Operations

pub fn isPowerOfTwo(int: anytype) bool;
pub fn floorPowerOfTwo(comptime T: type, value: T) T;
pub fn ceilPowerOfTwo(comptime T: type, value: T) !T;
pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) /* wider type */;
Example:
if (std.math.isPowerOfTwo(16)) { }  // true

const floor = std.math.floorPowerOfTwo(u32, 100);  // 64
const ceil = try std.math.ceilPowerOfTwo(u32, 100);  // 128

Type Utilities

pub fn minInt(comptime T: type) T;  // Minimum value for type
pub fn maxInt(comptime T: type) T;  // Maximum value for type

pub fn Log2Int(comptime T: type) type;      // Type to hold log2(T.bits)
pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type;
Example:
const min_i8 = std.math.minInt(i8);   // -128
const max_u16 = std.math.maxInt(u16); // 65535

const RangeType = std.math.IntFittingRange(0, 1000);  // u10

Casting

pub fn cast(comptime T: type, x: anytype) ?T;  // Safe cast, returns null on overflow
pub fn lossyCast(comptime T: type, x: anytype) T;  // Truncating cast
Example:
const safe = std.math.cast(u8, 300);  // null (overflow)
const ok = std.math.cast(u8, 100);    // 100

Other Functions

gcd, lcm

pub fn gcd(a: anytype, b: anytype) @TypeOf(a, b);  // Greatest common divisor
pub fn lcm(a: anytype, b: anytype) @TypeOf(a, b);  // Least common multiple

Gamma Functions

pub fn gamma(x: anytype) @TypeOf(x);   // Gamma function
pub fn lgamma(x: anytype) @TypeOf(x);  // Log-gamma function

Build docs developers (and LLMs) love