math
lib/math.vklib/math.vk Pure-Veko mathematical constants (compile-time folded), checked/saturating integer math, 64-bit bit operations, and double-precision IEEE-754 transcendentals. Zero capabilities required.
clamp-i64 = fn [x i64, lo i64, hi i64] i64
Clamps x to the inclusive range [lo, hi].
use [m = math]
if (m/clamp-i64 15 0 10) != 10 or (m/clamp-i64 -3 0 10) != 0 [ err 'clamp-i64' ] else [ .ok ]
add-checked = fn [a i64, b i64] i64
Checked 64-bit signed addition; returns err on overflow.
use [m = math]
ok1 = (m/add-checked 10 20) == 30
ov = m/add-checked/or m/i64-max 1 [ -1 ]
if (not ok1) or ov != -1 [ err 'add-checked' ] else [ .ok ]
sub-checked = fn [a i64, b i64] i64
Checked 64-bit signed subtraction; returns err on overflow.
mul-checked = fn [a i64, b i64] i64
Checked 64-bit signed multiplication; returns err on overflow.
add-sat = fn [a i64, b i64] i64
Saturating 64-bit signed addition (clamps at i64-min / i64-max).
sub-sat = fn [a i64, b i64] i64
Saturating 64-bit signed subtraction (clamps at i64-min / i64-max).
gcd = fn [a i64, b i64] i64
Greatest common divisor of a and b (non-negative).
use [m = math]
if (m/gcd 48 18) != 6 or (m/lcm 12 18) != 36 [ err 'gcd/lcm' ] else [ .ok ]
popcount = fn [x i64] i64
Counts the number of 1-bits in the 64-bit representation of x.
use [m = math]
if (m/popcount 0xF0F0) != 8 or (m/clz 1) != 63 or (m/ctz 8) != 3 [ err 'bitops' ] else [ .ok ]
clz = fn [x i64] i64
Counts leading zero bits in the 64-bit unsigned representation of x (64 for x == 0).
ctz = fn [x i64] i64
Counts trailing zero bits in the 64-bit representation of x (64 for x == 0).
floor = fn [x f64] f64
Largest integer <= x as f64.
use [m = math]
if (m/floor 2.9) != 2.0 or (m/floor -2.1) != -3.0 or (m/ceil 2.1) != 3.0 [ err 'floor/ceil' ] else [ .ok ]
sqrt = fn [x f64] f64
Double-precision square root lowered to hardware f64/sqrt (sqrtsd / f64.sqrt / fsqrt).
use [m = math]
d = m/abs-f64 ((m/sqrt 2.0) - m/sqrt2)
if d > 0.00000000000001 [ err 'sqrt mismatch' ] else [ .ok ]
exp = fn [x f64] f64
Exponential function e^x.
use [m = math]
d = m/abs-f64 ((m/exp 1.0) - m/e)
if d > 0.0000000000001 [ err 'exp mismatch' ] else [ .ok ]
ln = fn [x f64] f64
Natural logarithm ln(x) for x > 0.
use [m = math]
d = m/abs-f64 ((m/ln m/e) - 1.0)
if d > 0.0000000000001 [ err 'ln mismatch' ] else [ .ok ]
sin = fn [x f64] f64
Sine of x in radians.
use [m = math]
d1 = m/abs-f64 ((m/sin (m/pi / 2.0)) - 1.0)
d2 = m/abs-f64 ((m/cos m/pi) + 1.0)
if d1 > 0.000000000001 or d2 > 0.000000000001 [ err 'sin/cos mismatch' ] else [ .ok ]
atan = fn [x f64] f64
Arctangent of x in radians ([-pi/2, pi/2]).
use [m = math]
d = m/abs-f64 ((m/atan 1.0) - (m/pi / 4.0))
if d > 0.000000000001 [ err 'atan mismatch' ] else [ .ok ]