我在其他语言中使用过这个,但是lua似乎缺乏这个相当有用的功能。
你们其中一个漂亮的小狗能为我提供一个lua函数来获取传递给它的数字的符号吗?
答案 0 :(得分:12)
function math.sign(x)
if x<0 then
return -1
elseif x>0 then
return 1
else
return 0
end
end
答案 1 :(得分:8)
以防万一有人偶然发现这个:这是我的某种缩短版本:
function sign(x)
return x>0 and 1 or x<0 and -1 or 0
end
答案 2 :(得分:3)
我认为这个想法是返回1或-1来表示正面或负面。我不认为你会希望它返回0.可能会产生灾难性后果。想象一下,当它返回0时,尝试通过将符号乘以符号(x)来尝试更改值的符号。而不是更改符号,而是将值更改为0.。
我坚持
function sign(x)
return (x<0 and -1) or 1
end
答案 3 :(得分:0)
使用LuaJIT,如果将sign函数编译为JIT,则实际上速度更快:
function sign(x)
return math.max(math.min(x * 1e200 * 1e200, 1), -1)
end
原因是它避免了分支,而分支可能是昂贵的。双重乘法可确保即使输入在非正常范围内,结果也是正确的。不能使用无穷大,因为输入为零会产生NaN。
仅在x86中测试。我不能保证它是LuaJIT支持的其他处理器中最快的。
答案 4 :(得分:0)
与许多语言一样,Lua确实包含了基本的ternary operator,这是实现此目的的简单方法:
function sign(x)
return x < 0 ? -1 : x > 0 ? 1 : 0;//using basic lua ternary operator (nested)
end
答案 5 :(得分:0)
我构建这个是因为我需要对 -0
和 +0
以及所有其他版本都无法处理的 nan
进行精确处理。
这个想法是直接解释符号位并为此测试提供无分支版本。在纯 Lua 中,您必须使用 tostring(x) 检查 +-0。
local _sign_helper = ffi.new("union { double d; uint64_t ul; int64_t l; }[1]")
local function sign(num)
-- to get access to the bit representation of double
_sign_helper[0].d = num
-- reinterpret it as ulong to access the sign bit
-- 1. move the bit down to the first bit
-- 2. multiply by -2 to move the range from 0/1 to 0/-2
-- 4. add 1 to reduce the range to -1/1
-- one test version for NaN handling (might be faster, did not test.)
-- return num ~= num and num or (tonumber(bit.rshift(_sign_helper[0].ul, 63)) * -2 + 1)
-- branchless version: num - num will always be 0 except for nan.
return (tonumber(bit.rshift(_sign_helper[0].ul, 63)) * -2 + 1) * ((num - num + 1) / 1)
end
print("(number < 0)", sign(-3)) -- > -1
print("(number > 0)", sign(3)) -- > 1
print("(nan)", sign(0 / 0)) -- > nan
print("(-inf)", sign(-0 / 1)) -- > -1
print("(+inf)", sign(0 / 1)) -- > 1
print("(+0)", sign(0)) -- > 1
print("(-0)", sign(-0)) -- > -1
答案 6 :(得分:-1)
你也可以得到这样一个数字的符号:
x/ math.abs(x)
我只使用那个整数,因为Lua不区分整数和浮点数,我根本不会在Lua中使用它。
答案 7 :(得分:-1)
that 的变体可能是
function sign(x)
if x<0 then
return "-"
elseif x>0 then
return "+"
else
return ""
end
end
在数学上,符号是“+”或“-”(符号),而不是数字(如 +1 或 -1)
答案 8 :(得分:-3)
您可以像这样检查sign
:
i = -2
if i == math.abs(i) then -- or i >= 0
print "positive"
else
print "negative"
end