Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Zig Dictionary
  3. std.math (Math Functions)

std.math (Math Functions)

The Zig standard library module std.math provides mathematical functions needed for numerical computation, including absolute value, square root, exponentiation, trigonometric functions, and logarithms. It offers the equivalent of C's <math.h> in a type-safe Zig form, and also includes overflow-checked integer arithmetic and constants such as pi, e, inf, and nan. Use f32 or f64 for floating-point operations; the same functions are available both at compile time and at runtime.

Syntax

// -----------------------------------------------
// Summary of key std.math function syntax
// -----------------------------------------------

const std = @import("std");
const math = std.math;

// -----------------------------------------------
// Absolute value and sign
// -----------------------------------------------

// abs(x) — returns the absolute value of x (works for both integers and floats)
const a = math.abs(-42);        // 42
const b = math.abs(-3.14);      // 3.14

// sign(x) — returns the sign of x (positive: 1, negative: -1, zero: 0)
const s = math.sign(-7);        // -1

// -----------------------------------------------
// Square root and exponentiation
// -----------------------------------------------

// sqrt(x) — returns the square root of x (x >= 0 required)
const sq = math.sqrt(9.0);      // 3.0

// pow(T, base, exp) — returns base raised to the power of exp
const pw = math.pow(f64, 2.0, 10.0);  // 1024.0

// powi(T, base, exp) — integer exponentiation (integer types only)
const pi = math.powi(i32, 2, 8);  // 256 (overflow is returned as an error union)

// -----------------------------------------------
// Trigonometric functions
// -----------------------------------------------

// sin(x) — returns the sine of x (in radians)
const sv = math.sin(math.pi / 6.0);   // 0.5

// cos(x) — returns the cosine of x (in radians)
const cv = math.cos(math.pi / 3.0);   // 0.5

// tan(x) — returns the tangent of x (in radians)
const tv = math.tan(math.pi / 4.0);   // 1.0

// -----------------------------------------------
// Logarithms and exponentials
// -----------------------------------------------

// log(T, base, x) — returns the logarithm of x with the given base
const lg = math.log(f64, 10.0, 100.0);   // 2.0

// log2(x) — returns the base-2 logarithm
const l2 = math.log2(8.0);   // 3.0

// log10(x) — returns the base-10 logarithm
const l10 = math.log10(1000.0);  // 3.0

// exp(x) — returns e raised to the power of x
const ev = math.exp(1.0);    // approx. 2.718

// exp2(x) — returns 2 raised to the power of x
const e2 = math.exp2(8.0);   // 256.0

// -----------------------------------------------
// Rounding
// -----------------------------------------------

// floor(x) — largest integer less than or equal to x (round down)
const fl = math.floor(3.7);   // 3.0

// ceil(x) — smallest integer greater than or equal to x (round up)
const cl = math.ceil(3.2);    // 4.0

// round(x) — rounds to the nearest integer (0.5 rounds up)
const rn = math.round(2.5);   // 3.0

// trunc(x) — truncates the fractional part, rounding toward zero
const tr = math.trunc(-3.9);  // -3.0

// -----------------------------------------------
// Maximum, minimum, and clamping
// -----------------------------------------------

// max(a, b) — returns the larger of the two values
const mx = math.max(10, 20);   // 20

// min(a, b) — returns the smaller of the two values
const mn = math.min(10, 20);   // 10

// clamp(x, min, max) — constrains x to the range [min, max]
const clamped = math.clamp(150, 0, 100);  // 100

// -----------------------------------------------
// Constants
// -----------------------------------------------

// math.pi — the mathematical constant π (approx. 3.14159...)
// math.e  — the base of the natural logarithm e (approx. 2.71828...)
// math.inf(T) — positive infinity for type T
// math.nan(T) — NaN (Not a Number) for type T
const inf_val = math.inf(f64);
const nan_val = math.nan(f64);

// isNan(x) — returns true if x is NaN
const is_nan = math.isNan(nan_val);   // true

// isInf(x) — returns true if x is infinite
const is_inf = math.isInf(inf_val);   // true

Key functions and constants

Function / ConstantDescription
math.abs(x)Returns the absolute value of x. Works with both integer and floating-point types.
math.sign(x)Returns the sign of x: 1 if positive, -1 if negative, 0 if zero.
math.sqrt(x)Returns the square root of x. x must be a non-negative floating-point number.
math.pow(T, base, exp)Returns base raised to the power of exp. Type T must be a floating-point type.
math.powi(T, base, exp)Integer-only exponentiation. Returns an error on overflow.
math.sin(x)Returns the sine of x in radians. The return type matches the argument type.
math.cos(x)Returns the cosine of x in radians. The return type matches the argument type.
math.tan(x)Returns the tangent of x in radians. The return type matches the argument type.
math.log(T, base, x)Returns the logarithm of x with the given base. Type T must be a floating-point type.
math.log2(x)Returns the base-2 logarithm. Useful for computing bit counts and shift amounts.
math.log10(x)Returns the base-10 logarithm. Useful for computing the number of decimal digits.
math.exp(x)Returns e raised to the power of x (the exponential function).
math.exp2(x)Returns 2 raised to the power of x.
math.floor(x)Returns the largest integer value less than or equal to x, as a floating-point type.
math.ceil(x)Returns the smallest integer value greater than or equal to x, as a floating-point type.
math.round(x)Rounds to the nearest integer. 0.5 rounds up.
math.trunc(x)Truncates the fractional part, rounding toward zero.
math.max(a, b)Returns the larger of a and b.
math.min(a, b)Returns the smaller of a and b.
math.clamp(x, lo, hi)Returns x constrained to the range [lo, hi].
math.piThe mathematical constant π (approx. 3.14159265358979...).
math.eThe base of the natural logarithm e (approx. 2.71828182845904...).
math.inf(T)Returns positive infinity for type T.
math.nan(T)Returns NaN (Not a Number) for type T.
math.isNan(x)Returns true if x is NaN. The return type is bool.
math.isInf(x)Returns true if x is positive or negative infinity. The return type is bool.

Sample code

steinsgate_std_math.zig
// steinsgate_std_math.zig — demonstrates key std.math functions
// using characters from Steins;Gate
//
// Build:
//   zig run steinsgate_std_math.zig

const std = @import("std");
const math = std.math;

pub fn main() !void {

    // Get a writer for standard output
    const stdout = std.io.getStdOut().writer();

    // -----------------------------------------------
    // math.abs / math.sign — absolute value and sign
    // -----------------------------------------------

    try stdout.print("=== math.abs / math.sign ===\n\n", .{});

    // Okabe's world line divergence value (can be negative)
    const divergence_okabe: f64 = -0.337187;
    const abs_div = math.abs(divergence_okabe);
    const sign_div = math.sign(divergence_okabe);

    try stdout.print("  Okabe's divergence:        {d:.6}\n",   .{divergence_okabe});
    try stdout.print("  abs (absolute value):      {d:.6}\n",   .{abs_div});
    try stdout.print("  sign:                      {d:.0}\n\n", .{sign_div});

    // -----------------------------------------------
    // math.sqrt / math.pow — square root and exponentiation
    // -----------------------------------------------

    try stdout.print("=== math.sqrt / math.pow ===\n\n", .{});

    // Kurisu calculates the energy required for the time machine
    // E = base^exp [GJ]
    const base_energy: f64 = 3.0;
    const exp_factor: f64  = 8.0;
    const energy = math.pow(f64, base_energy, exp_factor);

    try stdout.print("  Kurisu's energy calculation: {d:.0}^{d:.0} = {d:.0} GJ\n\n",
        .{ base_energy, exp_factor, energy });

    // Daru calculates the diagonal length of the machine chassis using sqrt
    // Width 1.2m, height 0.9m: diagonal = sqrt(1.2^2 + 0.9^2)
    const width:  f64 = 1.2;
    const height: f64 = 0.9;
    const diagonal = math.sqrt(width * width + height * height);

    try stdout.print("  Daru's machine chassis (width {d:.1}m x height {d:.1}m)\n",
        .{ width, height });
    try stdout.print("  diagonal = sqrt({d:.2} + {d:.2}) = {d:.4}m\n\n",
        .{ width * width, height * height, diagonal });

    // -----------------------------------------------
    // math.sin / math.cos / math.pi — trigonometric functions
    // -----------------------------------------------

    try stdout.print("=== math.sin / math.cos / math.pi ===\n\n", .{});

    // Ruka's archery angle: θ = 30° = π/6 radians
    const theta: f64 = math.pi / 6.0;  // 30°
    const sin_v = math.sin(theta);
    const cos_v = math.cos(theta);

    try stdout.print("  Ruka's angle θ = π/6 (30°)\n",      .{});
    try stdout.print("  sin(θ) = {d:.6}\n",                  .{sin_v});
    try stdout.print("  cos(θ) = {d:.6}\n",                  .{cos_v});

    // With bow tension F = 50N, compute horizontal and vertical components
    const force: f64 = 50.0;
    try stdout.print("  Horizontal component at {d:.0}N: {d:.4}N\n",  .{ force, force * cos_v });
    try stdout.print("  Vertical component at {d:.0}N:   {d:.4}N\n\n", .{ force, force * sin_v });

    // -----------------------------------------------
    // math.log / math.log2 / math.log10 — logarithms
    // -----------------------------------------------

    try stdout.print("=== math.log / math.log2 / math.log10 ===\n\n", .{});

    // Mayuri uses logarithms to evaluate gacha rare item probability
    // p = 0.001 (0.1%): how many draws until a 50% cumulative chance?
    // n = log(0.5) / log(1 - 0.001)
    const p: f64 = 0.001;
    const target_prob: f64 = 0.5;
    const n_draws = math.log(f64, math.e, target_prob) /
                    math.log(f64, math.e, 1.0 - p);

    try stdout.print("  Mayuri's gacha (probability {d:.3})\n",        .{p});
    try stdout.print("  Draws needed for 50%+ chance: {d:.0}\n\n", .{math.ceil(n_draws)});

    // Express Faris's poker win rate in bits (information content)
    // win rate 0.25: information = -log2(0.25) bits
    const win_rate: f64 = 0.25;
    const info_bits = -math.log2(win_rate);

    try stdout.print("  Faris's win rate: {d:.2}\n",     .{win_rate});
    try stdout.print("  Information: {d:.2} bits\n\n",   .{info_bits});

    // -----------------------------------------------
    // math.floor / math.ceil / math.round / math.trunc — rounding
    // -----------------------------------------------

    try stdout.print("=== Rounding functions ===\n\n", .{});

    // Suzuha's time travel energy consumption (GJ), rounded each way
    const suzuha_energy: f64 = 42.718;

    try stdout.print("  Suzuha's energy: {d:.3} GJ\n",        .{suzuha_energy});
    try stdout.print("  floor (round down): {d:.0} GJ\n",     .{math.floor(suzuha_energy)});
    try stdout.print("  ceil  (round up):   {d:.0} GJ\n",     .{math.ceil(suzuha_energy)});
    try stdout.print("  round (nearest):    {d:.0} GJ\n",     .{math.round(suzuha_energy)});
    try stdout.print("  trunc (toward zero):{d:.0} GJ\n\n",   .{math.trunc(suzuha_energy)});

    // -----------------------------------------------
    // math.max / math.min / math.clamp — comparison and clamping
    // -----------------------------------------------

    try stdout.print("=== math.max / math.min / math.clamp ===\n\n", .{});

    // Compare and clamp IQ scores of lab members
    const iq_okabe:  i32 = 168;
    const iq_kurisu: i32 = 204;
    const iq_daru:   i32 = 155;

    try stdout.print("  Okabe IQ: {}, Kurisu IQ: {}, Daru IQ: {}\n",
        .{ iq_okabe, iq_kurisu, iq_daru });
    try stdout.print("  max(Okabe, Kurisu): {}\n", .{math.max(iq_okabe, iq_kurisu)});
    try stdout.print("  min(Okabe, Daru):   {}\n", .{math.min(iq_okabe, iq_daru)});

    // Clamp a game score to the range 0–999
    const raw_score: i32 = 1500;
    const clamped_score = math.clamp(raw_score, 0, 999);
    try stdout.print("  Raw score {} -> clamp(0, 999) = {}\n\n",
        .{ raw_score, clamped_score });

    // -----------------------------------------------
    // math.isNan / math.isInf — checking special values
    // -----------------------------------------------

    try stdout.print("=== math.isNan / math.isInf ===\n\n", .{});

    // Check for infinity and NaN (e.g., from division by zero)
    const divergence_inf = math.inf(f64);   // positive infinity (diverging world line)
    const divergence_nan = math.nan(f64);   // NaN (unobservable world line)

    try stdout.print("  divergence_inf = {d}\n",        .{divergence_inf});
    try stdout.print("  isInf(divergence_inf) = {}\n",  .{math.isInf(divergence_inf)});
    try stdout.print("  divergence_nan = {d}\n",        .{divergence_nan});
    try stdout.print("  isNan(divergence_nan) = {}\n\n", .{math.isNan(divergence_nan)});

    try stdout.print("El Psy Kongroo.\n", .{});
}
zig run steinsgate_std_math.zig
=== math.abs / math.sign ===

  Okabe's divergence:        -0.337187
  abs (absolute value):      0.337187
  sign:                      -1

=== math.sqrt / math.pow ===

  Kurisu's energy calculation: 3^8 = 6561 GJ

  Daru's machine chassis (width 1.2m x height 0.9m)
  diagonal = sqrt(1.44 + 0.81) = 1.5000m

=== math.sin / math.cos / math.pi ===

  Ruka's angle θ = π/6 (30°)
  sin(θ) = 0.500000
  cos(θ) = 0.866025
  Horizontal component at 50N: 43.3013N
  Vertical component at 50N:   25.0000N

=== math.log / math.log2 / math.log10 ===

  Mayuri's gacha (probability 0.001)
  Draws needed for 50%+ chance: 693

  Faris's win rate: 0.25
  Information: 2.00 bits

=== Rounding functions ===

  Suzuha's energy: 42.718 GJ
  floor (round down): 42 GJ
  ceil  (round up):   43 GJ
  round (nearest):    43 GJ
  trunc (toward zero):42 GJ

=== math.max / math.min / math.clamp ===

  Okabe IQ: 168, Kurisu IQ: 204, Daru IQ: 155
  max(Okabe, Kurisu): 204
  min(Okabe, Daru):   155
  Raw score 1500 -> clamp(0, 999) = 999

=== math.isNan / math.isInf ===

  divergence_inf = inf
  isInf(divergence_inf) = true
  divergence_nan = nan
  isNan(divergence_nan) = true

El Psy Kongroo.

Overview

Zig's std.math is a standard library module that covers all the mathematical functions and constants needed for numerical computation. Use math.abs for absolute value, math.sqrt for square roots, and math.pow (floating-point) or math.powi (integer, with overflow checking) for exponentiation. The trigonometric functions (math.sin, math.cos, math.tan) accept arguments in radians and are typically used with the math.pi constant. For logarithms, math.log(T, base, x) accepts an arbitrary base, and math.log2 and math.log10 are provided as convenient shortcuts. Rounding is handled by floor (round down), ceil (round up), round (round to nearest), and trunc (truncate toward zero) — choose based on your use case. Range clamping is available in a single call with math.clamp. To work with special floating-point values, use math.inf and math.nan to create them, and math.isInf and math.isNan to check for them. For integer arithmetic in general, see Integer Types; for details on floating-point, see Floating-Point Types.

If you find any errors or copyright issues, please .