algorithm

Get 1, 0, -1 as positive, zero, or negative for an integer with math only


I have a situation where I'm performing a calculate over a huge number of rows, and I can really increase the performance if I can eschew a conditional statement.

What I need is for a given positive, zero, or negative integer I want the result 1, 0, -1 respectively.

So if I do col/ABS(col), I will get 1 for a positive number, and -1 for a negative number, but of course if col equals 0 then I'll get an error. I can't get an error.

This seems simple enough, but I can't wrap my ahead around it.


Solution

  • col/max(1, abs(col))

    Ugly but works. For integers, that is. For floating point values where there's no well-defined smallest positive value, you're stuck unless the language allows you to look into it as a bit sequence, then you can just do the same with the sign flag and the significand.

    Whether this helps optimising anything is highly debatable though. It certainly makes things harder to read.