9

I've used this in other languages, but lua seems to be lacking this rather useful function.

Could one of you nice chappies provide me a lua function to get the sign of the number passed to it?

0

8 Answers 8

17
function math.sign(x)
   if x<0 then
     return -1
   elseif x>0 then
     return 1
   else
     return 0
   end
end
1
  • 3
    IMO, change it set only if not already available and namespace pollution is OK: math.sign = math.sign or function(x) return x<0 and -1 or x>0 and 1 or 0 end (of course, this relies on other libraries using the same behaviour if they define the same function)
    – Deco
    Feb 4, 2014 at 6:29
13

Just in case anyone stumbles on this one:, here's my somehow shorter version:

function sign(x)
  return x>0 and 1 or x<0 and -1 or 0
end
0
8

I think the idea is to return 1 or -1 to represent positive or negative. I don't think you would want it to return 0. Could have disastrous effects. Imagine trying to change the sign of a value by multiplying it by sign(x) when it returns 0. Instead of changing the sign you'd change the value to 0.

I'd stick with

function sign(x)
  return (x<0 and -1) or 1
end
0

With LuaJIT, if the sign function gets JIT-compiled, this is actually faster:

function sign(x)
  return math.max(math.min(x * 1e200 * 1e200, 1), -1)
end

The reason is that it avoids branches, which can be expensive. The double multiplication ensures that the result is correct even with inputs in the denormal range. Infinity can't be used because with an input of zero, it would produce NaN.

Tested in x86 only. I can't guarantee that it's the fastest in other processors supported by LuaJIT.

0

I built this one because I needed exact handling for -0 and +0 as well as for nan which all the other versions do not handle.

The idea is to interpret the sign bit directly and have a branchless version for this test. In pure Lua you'd have to go with tostring(x) checks +-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  


-1

You can also get the sign of a number like this:

x/ math.abs(x)

I'd only use that one for integers and since Lua doesn't distinguish ints from floats, I'd not use it in Lua at all.

1
  • Oh, div by zero possible ;)
    – Chris
    Apr 17, 2020 at 0:22
-1

A variation of that could be

function sign(x)
   if x<0 then
     return "-"
   elseif x>0 then
     return "+"
   else
     return ""
   end
end

Mathematically, the sign is '+' or '-' (a symbol), not a number (as +1 or -1)

-2

You can check for the sign like this:

i = -2
if i == math.abs(i) then -- or i >= 0
   print "positive"
else
   print "negative"
end
5
  • 3
    -1: Why would you call a function and do a compare when you can check for negativeness with a single compare operator? In Lua, I don't believe this can fail, but in other languages this may fail if i is type int and math.abs returns a double, for example. Don't write more code than necessary. Nov 15, 2010 at 16:26
  • @Jonathan: do you mean why call math.abs? I had put the comparison >= in a comment as an alternative. You can choose whatever you like. Nov 15, 2010 at 16:38
  • I see that. I don't think it should be an alternative but the only answer. Nov 15, 2010 at 17:12
  • @Jonathan: programming is not just writing fast code. It's also about expressiveness. Personally, I prefer the first way. Nov 15, 2010 at 17:30
  • 2
    @Nick It does not express intent anywhere near as clearly as lhs's code. It's trying to be clever, which in general is a bad habit.
    – Mud
    Jul 9, 2012 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.