f64 userdatas have the following arithmetic operations:
add, sub, mul, div, mod, min, max, idiv
We can create a few additional useful operations using just these.
local function ud_floor(x) return x-x:mod(1) end local function ud_floor(x) return x:idiv(1) end -- Alternative. Faster for userdatas smaller than ~270 elements. local function ud_round(x) x += 0.5 return x-x:mod(1) end local function ud_ceil(x) return (0-x):mod(1)-x end local function ud_abs(x) return x:max(0-x) end local function ud_sign(x) return x/(x:max(0-x)) end -- Not zero-safe. local function ud_positive(x) return x:max(0)/x end -- Not zero-safe. local function ud_negative(x) return x:min(0)/x end -- Not zero-safe. local function ud_tern(c,a,b) return a*c+b*(1-c) end |
Here are some other useful userdata math tricks:
local function sum(x) return vec(0):add(x,true,0,0,1,1,0,#x)[0] end local function prod(x) return vec(1):mul(x,true,0,0,1,1,0,#x)[0] end -- If you have a matrix with a vector in each row, and you'd like to get their dot products -- with a single vector, you can do so like this: local function dot_all(v,m) return m:matmul(v:transpose()) end -- luchak discovered this prefix sum operation. local function psum(v) return v:add(v,true,0,1,1,1,1,#v-1) end -- which is useful for creating a linear sequence with a specific slope. -- v[n] = init+n*step local function linstep(v,init,step) return v:copy(step,true):copy(init,true,0,0,1):add(v,true,0,1,1,1,1,#v-1) end |
[Please log in to post a comment]