Skip to main content

Math Library

The Math builtin library provides everything you need for numeric work in AdeshLang: mathematical constants, arithmetic, rounding, exponentiation and logarithms, trigonometry, hyperbolic functions, random number generation, number-theory helpers (GCD, LCM, factorials, combinations), floating-point utilities, and special functions.

It exposes two namespaces:

NamespaceWhat it provides
MathFunctions and constants for real (floating-point) numbers.
cmathFunctions for complex numbers (a + b·j), plus convenience conversions.

Importing the library

import Math; // real math — recommended for most programs
import cmath; // complex math

import { sqrt, pow } from "Math"; // selective import also works
note

Both import Math and import math bind the same namespace. The cmath namespace is imported with its exact lowercase name.

When to use which namespace

  • Use Math for everyday numeric calculations — geometry, statistics, simulations, financial math, rounding, and randomness.
  • Use cmath when you need complex numbers — for example, electrical engineering, signal processing, quantum mechanics, or math where negative square roots must be representable.
  • cmath functions accept plain numbers too; a real number is treated as a complex value with an imaginary part of 0.

Constants

Math constants

ConstantApproximate valueDescription
Math.PI / Math.pi3.141592653589793π, the ratio of a circle's circumference to its diameter.
Math.E / Math.e2.718281828459045Euler's number, base of natural logarithms.
Math.TAU / Math.tau6.2831853071795862π, a full turn in radians.
Math.SQRT21.4142135623730951Square root of 2.
Math.SQRT1_20.70710678118654761/√2 (square root of one-half).
Math.LN20.6931471805599453Natural logarithm of 2.
Math.LN102.302585092994046Natural logarithm of 10.
Math.infInfinityPositive infinity.
Math.nanNaNNot-a-Number.
import Math;
print(Math.PI); // 3.141592653589793
print(Math.E); // 2.718281828459045
print(Math.SQRT1_2); // 0.7071067811865476

cmath constants

ConstantValueDescription
cmath.pi3.141592653589793π.
cmath.e2.718281828459045Euler's number.
cmath.tau6.2831853071795862π.
cmath.infInfinityReal infinity.
cmath.nanNaNReal not-a-number.
cmath.infj0 + ∞jComplex infinity.
cmath.nanj0 + NaN·jComplex not-a-number.

Methods: Random Number Generation

For simulations, games, sampling, and testing. All functions can be made deterministic by calling Math.seed first.

FunctionDescriptionParametersReturns
Math.random()Random float in [0, 1)number
Math.seed(seed)Seed the global RNG so later random calls are reproducibleseed: numbernull
Math.randomInt(min, max)Random integer in [min, max] (inclusive on both ends)min: number, max: numbernumber
Math.randomRange(min, max)Random float in [min, max) (max excluded)min: number, max: numbernumber
import Math;

Math.seed(42); // deterministic from now on
print(Math.random()); // 0.3745... (some float in [0, 1))

let die = Math.randomInt(1, 6); // dice roll: an integer from 1 to 6
let temp = Math.randomRange(20.0, 30.0); // temperature in [20, 30)
tip

Call Math.seed(value) before a batch of random calls to get the exact same sequence on every run — useful for reproducible tests and simulations.


Methods: Rounding, Sign & Integer Helpers

Use these to convert floats to whole numbers or to describe the sign of a value.

FunctionDescriptionParametersReturns
Math.floor(x)Round down to the nearest integerx: numbernumber
Math.ceil(x)Round up to the nearest integerx: numbernumber
Math.round(x)Round to the nearest integer (half rounds away from zero)x: numbernumber
Math.trunc(x)Remove the fractional part (round toward zero)x: numbernumber
Math.sign(x)Sign of a value: 1 for positive, -1 for negative, 0 for zerox: numbernumber
Math.isqrt(n)Integer square root: largest integer k with k² ≤ nn: numbernumber
import Math;
print(Math.floor(3.7)); // 3
print(Math.ceil(3.1)); // 4
print(Math.round(3.5)); // 4
print(Math.trunc(-3.9)); // -3
print(Math.sign(-10)); // -1
print(Math.sign(0)); // 0
print(Math.sign(10)); // 1
print(Math.isqrt(26)); // 5
note

Math.isqrt(n) returns 0 for negative input. Math.trunc differs from Math.floor: trunc(-3.9)-3, while floor(-3.9)-4.


Methods: Basic Arithmetic

Core operations on one or more numbers.

FunctionDescriptionParametersReturns
Math.abs(x)Absolute value of xx: numbernumber
Math.fabs(x)Alias of Math.abs (float absolute value)x: numbernumber
Math.min(...values)Smallest of the given values (at least one required)...values: number[]number
Math.max(...values)Largest of the given values (at least one required)...values: number[]number
Math.pow(x, y)x raised to the power yx: number, y: numbernumber
Math.sqrt(x)Square root of xx: numbernumber
Math.cbrt(x)Cube root of xx: numbernumber
Math.hypot(...coords)Euclidean length of a vector; √(a² + b² + …). Returns 0 with no arguments...coords: number[]number
Math.clamp(val, min, max)Restrict val to the range [min, max]val: number, min: number, max: numbernumber
Math.lerp(a, b, t)Linear interpolation: a + (b - a) * ta: number, b: number, t: numbernumber
import Math;
print(Math.abs(-42)); // 42
print(Math.min(3, -10, 20)); // -10
print(Math.max(3, -10, 20)); // 20
print(Math.pow(2, 8)); // 256
print(Math.sqrt(81)); // 9
print(Math.cbrt(27)); // 3
print(Math.hypot(3, 4)); // 5
print(Math.clamp(45, 0, 10)); // 10
print(Math.lerp(10, 20, 0.5)); // 15

Methods: Exponentials, Roots & Logarithms

For growth/decay models, sound levels (dB), information theory, and any log-scale math.

FunctionDescriptionParametersReturns
Math.exp(x)Euler's number raised to x ()x: numbernumber
Math.exp2(x)2 raised to the power x ()x: numbernumber
Math.expm1(x)eˣ - 1 (accurate for very small x)x: numbernumber
Math.log(x)Natural logarithm of x (base e)x: numbernumber
Math.log(x, base)Logarithm of x in the given basex: number, base: numbernumber
Math.log2(x)Base-2 logarithmx: numbernumber
Math.log10(x)Base-10 logarithmx: numbernumber
Math.log1p(x)ln(1 + x) (accurate for very small x)x: numbernumber
import Math;
print(Math.exp(1)); // 2.718281828459045
print(Math.log(Math.E)); // 1
print(Math.log(8, 2)); // 3
print(Math.log10(100)); // 2
print(Math.log2(32)); // 5
print(Math.expm1(1)); // 1.718281828459045
print(Math.log1p(1)); // 0.6931471805599453

Methods: Trigonometry

All trigonometric functions work in radians. Use degToRad/radians to convert from degrees when needed.

FunctionDescriptionParametersReturns
Math.sin(x)Sine of an angle (radians)x: numbernumber
Math.cos(x)Cosine of an angle (radians)x: numbernumber
Math.tan(x)Tangent of an angle (radians)x: numbernumber
Math.asin(x)Arc sine; inverse of sinex: numbernumber
Math.acos(x)Arc cosine; inverse of cosinex: numbernumber
Math.atan(x)Arc tangent; inverse of tangentx: numbernumber
Math.atan2(y, x)Arc tangent of y / x, returning an angle in the correct quadranty: number, x: numbernumber
import Math;
print(Math.sin(Math.PI / 2)); // 1
print(Math.cos(0)); // 1
print(Math.tan(0)); // 0
print(Math.asin(1)); // 1.5707963267948966 (π/2)
print(Math.acos(1)); // 0
print(Math.atan(1)); // 0.7853981633974483 (π/4)
print(Math.atan2(1, 1)); // 0.7853981633974483
tip

Prefer Math.atan2(y, x) over Math.atan(y / x) — it handles the case x = 0 and always picks the correct quadrant, which is essential when computing directions and angles between points.


Methods: Hyperbolic Functions

The hyperbolic functions (sinh, cosh, tanh) describe the shape of a hanging cable and appear in physics, geometry of hyperbolic space, and exponential smoothing. The a-prefixed versions are their inverses.

FunctionDescriptionParametersReturns
Math.sinh(x)Hyperbolic sinex: numbernumber
Math.cosh(x)Hyperbolic cosinex: numbernumber
Math.tanh(x)Hyperbolic tangentx: numbernumber
Math.asinh(x)Inverse hyperbolic sinex: numbernumber
Math.acosh(x)Inverse hyperbolic cosinex: numbernumber
Math.atanh(x)Inverse hyperbolic tangentx: numbernumber
import Math;
let v = 1.0;
print(Math.sinh(v)); // 1.1752011936438014
print(Math.cosh(v)); // 1.5430806348152437
print(Math.tanh(v)); // 0.7615941559557649
print(Math.asinh(Math.sinh(v))); // ~1.0 (round-trip)
print(Math.acosh(Math.cosh(v))); // ~1.0 (round-trip)
print(Math.atanh(Math.tanh(v))); // ~1.0 (round-trip)

Methods: Angle Conversion

FunctionDescriptionParametersReturns
Math.degToRad(deg)Convert degrees → radiansdeg: numbernumber
Math.radians(deg)Alias of Math.degToRaddeg: numbernumber
Math.radToDeg(rad)Convert radians → degreesrad: numbernumber
Math.degrees(rad)Alias of Math.radToDegrad: numbernumber
import Math;
let rad = Math.degToRad(180); // 3.141592653589793
print(rad);
print(Math.radToDeg(rad)); // 180
print(Math.degrees(Math.PI)); // 180

Methods: Number Theory

Discrete-math helpers useful in combinatorics, cryptography teaching, modular arithmetic, and algorithm problems.

FunctionDescriptionParametersReturns
Math.gcd(...values)Greatest common divisor of all values. gcd() with no args returns 0...values: number[]number
Math.lcm(...values)Least common multiple of all values. lcm() with no args returns 1...values: number[]number
Math.factorial(n)n! = 1·2·3·…·n. Returns 0 for negative nn: numbernumber
Math.comb(n, k)Combinations: number of ways to choose k items from n (order does not matter). Returns 0 when k is invalidn: number, k: numbernumber
Math.perm(n, k)Permutations: number of ways to arrange k items picked from n (order matters). Returns 0 when k is invalidn: number, k: numbernumber
import Math;
print(Math.gcd(24, 36)); // 12
print(Math.gcd(24, 36, 60)); // 12
print(Math.lcm(24, 36)); // 72
print(Math.factorial(5)); // 120
print(Math.comb(5, 2)); // 10
print(Math.perm(5, 2)); // 20

Methods: Floating-Point Utilities

Fine-grained control over IEEE-754 floating-point behavior for scientific code and precise numeric algorithms.

FunctionDescriptionParametersReturns
Math.fma(x, y, z)Fused multiply-add: computes x·y + z with a single roundingx: number, y: number, z: numbernumber
Math.fmod(x, y)Floating-point remainder of x / y (truncated division)x: number, y: numbernumber
Math.modf(x)Split into (fractional_part, integer_part)x: numbertuple
Math.remainder(x, y)IEEE remainder of x / y (rounded division)x: number, y: numbernumber
Math.copysign(x, y)Magnitude of x with the sign of yx: number, y: numbernumber
Math.frexp(x)Split into (mantissa, exponent) such that x = mantissa · 2ᵉᵡᵖx: numbertuple
Math.ldexp(x, i)Compute x · 2ⁱ (inverse of frexp)x: number, i: numbernumber
Math.nextafter(x, y)Next representable float after x toward yx: number, y: numbernumber
Math.nextafter(x, y, steps)steps representable floats after x toward yx: number, y: number, steps: numbernumber
Math.ulp(x)Unit in the last place — size of the gap between x and the next floatx: numbernumber
import Math;
print(Math.fma(2, 3, 4)); // 10
print(Math.fmod(5.3, 2.0)); // 1.3
print(Math.modf(3.75)); // (0.75, 3.0)
print(Math.copysign(3, -1)); // -3
print(Math.frexp(12.0)); // (0.75, 4) → 0.75 · 2⁴ = 12
print(Math.ldexp(0.75, 4)); // 12
note

Math.modf and Math.frexp return a tuple, so destructure or index them like let (frac, integral) = Math.modf(x); or Math.modf(x)[0].


Methods: Value Classification

Predicates to safely inspect numbers before using them — the idiomatic way to guard against NaN/infinity in AdeshLang.

FunctionDescriptionParametersReturns
Math.isclose(a, b, rel_tol?, abs_tol?)Whether a and b are close within relative tolerance rel_tol (default 1e-09) and/or absolute tolerance abs_tol (default 0)a: number, b: number, rel_tol?: number, abs_tol?: numberboolean
Math.isfinite(x) / Math.isFinite(x)true if x is a finite number (not NaN/infinity)x: numberboolean
Math.isinf(x) / Math.isInf(x)true if x is ±Infinityx: numberboolean
Math.isnan(x) / Math.isNaN(x)true if x is NaN (not a number)x: numberboolean
import Math;
print(Math.isclose(0.1 + 0.2, 0.3)); // true (handles floating-point error)
print(Math.isfinite(3)); // true
print(Math.isinf(Math.inf)); // true
print(Math.isnan(Math.nan)); // true
tip

Never compare floats directly with ==. Use Math.isclose(a, b) for approximate comparisons in tests and financial calculations.


Methods: Array / Statistical Helpers

Operate on numeric arrays (iterables) for statistics, linear algebra, and signal processing.

FunctionDescriptionParametersReturns
Math.dist(p, q)Euclidean distance between two equal-length numeric vectorsp: array, q: arraynumber
Math.fsum(iterable)Accurate floating-point sum (Kahan/Neumaier compensated summation, reduces rounding error)iterable: arraynumber
Math.prod(iterable, start?)Product of all elements, optionally starting from start (default 1)iterable: array, start?: numbernumber
Math.sumprod(p, q)Sum of element-wise products of two arrays (Σ pᵢ·qᵢ, the dot product)p: array, q: arraynumber
import Math;
let a = [1, 2, 3];
let b = [4, 5, 6];

print(Math.dist([0, 0], [3, 4])); // 5
print(Math.fsum([0.1, 0.2, 0.3])); // 0.6
print(Math.prod([1, 2, 3, 4])); // 24
print(Math.sumprod(a, b)); // 32 (1·4 + 2·5 + 3·6)

Methods: Special Functions

Advanced mathematical functions for statistics, physics, and engineering.

FunctionDescriptionParametersReturns
Math.erf(x)Error function — the CDF of the standard normal distributionx: numbernumber
Math.erfc(x)Complementary error function: 1 - erf(x)x: numbernumber
Math.gamma(x)Gamma function — generalization of the factorial to real numbers (Γ(n) = (n-1)! for integers)x: numbernumber
Math.lgamma(x)Natural logarithm of the absolute value of the gamma functionx: numbernumber
import Math;
print(Math.erf(1.0)); // 0.8427007929497149
print(Math.erfc(1.0)); // 0.15729920705028513
print(Math.gamma(5.0)); // 24 (= 4!)
print(Math.lgamma(5.0)); // 3.1780538303479458 (ln(24))

Methods: Formatting

FunctionDescriptionParametersReturns
Math.formatDecimal(n, precision?)Format a number as a full decimal string with the given number of digits after the point (default 6)n: number, precision?: numberstring
import Math;
let huge = 2.43290200817664e18;
print(huge); // 2.43290200817664e18 (scientific)
print(Math.formatDecimal(huge, 0)); // "2432902008176640000"
print(Math.formatDecimal(123.456, 1)); // "123.5"

The cmath namespace (Complex Numbers)

The cmath namespace implements complex-number math. Complex values are printed like real + imag·j (e.g., 0.0 + 2.0j), and every function here accepts either a complex value or a plain number.

import cmath;
let z = cmath.sqrt(-4); // 0.0 + 2.0j
print(z);
print(cmath.phase(z)); // 1.5707963267948966 (π/2)

cmath methods

FunctionDescriptionParametersReturns
cmath.sqrt(z)Complex square rootz: complex|numbercomplex
cmath.exp(z)Complex exponential eᶻz: complex|numbercomplex
cmath.log(z)Complex natural logarithmz: complex|numbercomplex
cmath.log(z, base)Complex logarithm in the given basez: complex|number, base: numbercomplex
cmath.log10(z)Complex base-10 logarithmz: complex|numbercomplex
cmath.sin(z)Complex sinez: complex|numbercomplex
cmath.cos(z)Complex cosinez: complex|numbercomplex
cmath.tan(z)Complex tangentz: complex|numbercomplex
cmath.asin(z)Complex arc sinez: complex|numbercomplex
cmath.acos(z)Complex arc cosinez: complex|numbercomplex
cmath.atan(z)Complex arc tangentz: complex|numbercomplex
cmath.sinh(z)Complex hyperbolic sinez: complex|numbercomplex
cmath.cosh(z)Complex hyperbolic cosinez: complex|numbercomplex
cmath.tanh(z)Complex hyperbolic tangentz: complex|numbercomplex
cmath.asinh(z)Complex inverse hyperbolic sinez: complex|numbercomplex
cmath.acosh(z)Complex inverse hyperbolic cosinez: complex|numbercomplex
cmath.atanh(z)Complex inverse hyperbolic tangentz: complex|numbercomplex
cmath.phase(z)Phase (argument, angle) of z in radiansz: complex|numbernumber
cmath.polar(z)Polar form as (radius, phase) tuplez: complex|numbertuple
cmath.rect(r, phi)Build a complex number from polar (radius, phase)r: number, phi: numbercomplex
cmath.isclose(a, b, rel_tol?, abs_tol?)Approximate equality for complex numbersa, b, rel_tol?, abs_tol?boolean
cmath.isfinite(z) / cmath.isFinite(z)true if both real and imaginary parts are finitez: complex|numberboolean
cmath.isinf(z) / cmath.isInf(z)true if either part is infinitez: complex|numberboolean
cmath.isnan(z) / cmath.isNaN(z)true if either part is NaNz: complex|numberboolean
import cmath;

let z = cmath.sqrt(-4); // 0.0 + 2.0j
print(cmath.cos(z)); // -3.35618... + 0.0j (cos(2j))
print(cmath.polar(z)); // (2.0, 1.5707963267948966)
print(cmath.rect(2.0, Math.PI / 2)); // 0.0 + 2.0j (back to rectangular)
print(cmath.isfinite(z)); // true
print(cmath.isinf(cmath.infj)); // true

Complete example

A single program using several areas of the library together:

import Math;

fn probability_of_at_least_heads(n, k) {
// P(at least k heads in n fair coin tosses)
let total = Math.pow(2.0, n);
let favorable = 0;
for i in range(k, n + 1) {
favorable += Math.comb(n, i);
}
return favorable / total;
}

print("--- Constants ---");
print("PI:", Math.PI, "E:", Math.E);

print("\n--- Random (seeded, reproducible) ---");
Math.seed(7);
print("dice:", Math.randomInt(1, 6));
print("unit float:", Math.random());

print("\n--- Geometry ---");
print("distance:", Math.hypot(3, 4));
print("angle:", Math.radToDeg(Math.atan2(1, 1)), "deg");

print("\n--- Probability ---");
print("P(at least 3 heads in 5 tosses):", probability_of_at_least_heads(5, 3));

print("\n--- Precision ---");
print("fsum:", Math.fsum([0.1, 0.2, 0.3]));
print("isclose:", Math.isclose(0.1 + 0.2, 0.3));
print("formatted:", Math.formatDecimal(Math.factorial(20), 0));

Notes & edge cases

  • All Math functions return f64 (number) and accept any numeric type; non-numeric arguments raise an error.
  • Trigonometric and hyperbolic functions expect/return radians unless converted with degToRad/radToDeg.
  • Math.randomInt(min, max) includes both min and max; Math.randomRange and Math.random exclude the upper bound.
  • Math.factorial of a negative number, Math.comb/Math.perm with an invalid k, and Math.isqrt of a negative number all return 0.
  • Math.gcd() with no arguments returns 0; Math.lcm() with no arguments returns 1; Math.hypot() with no arguments returns 0.
  • Math.modf and Math.frexp return tuples — index them or destructure.
  • Math.log(x) defaults to the natural logarithm; pass a second argument for another base.
  • For reproducible randomness, always call Math.seed(...) at the start of the program.

Source & examples

  • Implementation: src/runtime/stdlib_src/math/mod.rs
  • Runnable examples: examples/Libraries/math/ (math_demo.adesh, cmath_demo.adesh, all.adesh, trigonometry.adesh, logs_and_powers.adesh, min_max_abs_sign.adesh, random_and_rounding.adesh)