Alex
2014-05-24 01:18:14 UTC
Mike, could you consider adding a math.sign function to LuaJIT?
I've come across a few places in my projects where I need a sign function,
that is, a function that returns 1 for positive values, -1 for negative
values, and 0 for zero.
A naive function goes like this:
local function sign(x)
if x < 0 then
return -1
elseif x > 0 then
return 1
else
return 0
end
end
However, that's three branches for a relatively simple operation. Granted,
the zero branch is probably not going to be taken a whole lot, but still.
I've seen other ways of doing it, but they either rely on the number being
an integer or have some other limitation (ex. `abs(x) / x` is branchless
and simple, but fails for 0.) It seems like the SSE instruction set should
have something for this, but I'm not familiar with it.
Is it possible and feasible to implement this, and if so, could you?
I've come across a few places in my projects where I need a sign function,
that is, a function that returns 1 for positive values, -1 for negative
values, and 0 for zero.
A naive function goes like this:
local function sign(x)
if x < 0 then
return -1
elseif x > 0 then
return 1
else
return 0
end
end
However, that's three branches for a relatively simple operation. Granted,
the zero branch is probably not going to be taken a whole lot, but still.
I've seen other ways of doing it, but they either rely on the number being
an integer or have some other limitation (ex. `abs(x) / x` is branchless
and simple, but fails for 0.) It seems like the SSE instruction set should
have something for this, but I'm not familiar with it.
Is it possible and feasible to implement this, and if so, could you?
--
Sincerely,
Alex Parrill
Sincerely,
Alex Parrill