std/math
Math over int and real, plus a random number generator. Import with
import "std/math";. Available everywhere.
Integer helpers take and return int. Floating-point helpers take and return
real, and most carry an f suffix (abs vs absf). The exponential and
trigonometric functions are backed by the platform math library.
Constants
Section titled “Constants”let PI = 3.141592653589793;let TAU = PI * 2.0;let E = 2.718281828459045;let degrees = radians * 180.0 / math.PI;Random numbers
Section titled “Random numbers”real random() # uniform in [0, 1)void seed(s: int) # seed the generator; same seed, same sequencerandom returns a uniform real in [0, 1). It is deterministic per seed and
not suitable for cryptography.
math.seed(7);let dice = (math.random() * 6.0) as int + 1; # 1 to 6Integer functions
Section titled “Integer functions”int abs(n: int) # absolute valueint sign(n: int) # -1, 0, or 1int min(a: int, b: int) # smaller of the twoint max(a: int, b: int) # larger of the twoint clamp(v: int, lo: int, hi: int) # v limited to [lo, hi]int pow(base: int, exp: int) # base to the power exp; 0 if exp < 0int gcd(a: int, b: int) # greatest common divisor, never negativemath.abs(-5) # 5math.clamp(12, 0, 9) # 9math.pow(2, 10) # 1024math.gcd(48, 36) # 12Real functions
Section titled “Real functions”real absf(x: real) # absolute valuereal signf(x: real) # -1.0, 0.0, or 1.0real minf(a: real, b: real) # smaller of the tworeal maxf(a: real, b: real) # larger of the tworeal clampf(v: real, lo: real, hi: real) # v limited to [lo, hi]real floorf(x: real) # round downreal ceilf(x: real) # round upreal roundf(x: real) # round half away from zeroreal truncf(x: real) # round toward zeroreal sqrtf(x: real) # square rootreal cbrt(x: real) # cube rootreal powf(base: real, exponent: real) # base to the power exponentreal fmod(x: real, y: real) # remainder of x / y, sign of xreal hypot(x: real, y: real) # sqrt(x*x + y*y), without overflowmath.floorf(2.7) # 2.0math.roundf(-2.5) # -3.0math.fmod(7.5, 2.0) # 1.5math.hypot(3.0, 4.0) # 5.0Exponentials and logarithms
Section titled “Exponentials and logarithms”real exp(x: real) # e to the xreal log(x: real) # natural logreal log2(x: real) # base-2 logreal log10(x: real) # base-10 logmath.log2(1024.0) # 10.0Trigonometry
Section titled “Trigonometry”All angles are in radians.
real sin(x: real) real cos(x: real) real tan(x: real)real asin(x: real) real acos(x: real) real atan(x: real)real atan2(y: real, x: real) # angle of the point (x, y); handles quadrantsreal sinh(x: real) real cosh(x: real) real tanh(x: real)let pi = math.acos(-1.0);math.sin(pi / 2.0) # 1.0math.atan2(1.0, 1.0) # 0.785398... (pi / 4)