# Equation that produces negative one if x is less than zero and vice versa

I have tried coming up with something but i couldn't in the end...

basically i want something to produce -1 or 1. given value of x will not be equal to zero at any point. But if you want to add that, do so in another example. I'd like to have both, but need first one.

so

if x=2
y=1
if x=-3435
y=-1


what i've tried:

well i thought i am gonna need a way to make any number a one regardless of sign right. so..

x-((x*-1)) working on it :D

can't use square root, absolute value(unless there is a equation for deriving absolute value).

• i couldn't find tag suitable – Muhammad Umer Aug 9 '13 at 5:10
• would it be possible to do it without absolute value or is there a way to find absolute value using math only. No programming etc. – Muhammad Umer Aug 9 '13 at 5:33

It sounds like you want the sign function. Considering the restriction that $x \neq 0$, you could just write

$$\frac{x}{|x|}$$

• check my comment thanks... – Muhammad Umer Aug 9 '13 at 5:34
• @MuhammadUmer What do you mean "find absolute value using math only"? The absolute value is defined mathematically just to be $|x| = x$ when $x \geq 0$, and $|x| = -x$ else. – user61527 Aug 9 '13 at 5:35
• i am trying to write a equation that can be run in a program that calculate this. i could use conditionals like you said, or use builtin methods. But i am wondering is it really not possible to derive absolute value without ifsss. (greater than zero then this etc..) – Muhammad Umer Aug 9 '13 at 5:38
• You could also use $|x| = \sqrt{x^2}$, but this will likely increase execution time if it's called a lot. – user61527 Aug 9 '13 at 5:39
• Depending on whether your programming language has bitwise operations, you could use as the fastest method of absolute value (Four operations) the following: (Described in C) (y = x >> 31; x ^= y; x += y & 1;) (In words) (Store the value of arithmetically right-shifting your value (x) by 31 bits to a new variable, y. Store the xor of y and x to x. Store the sum of x and the bitwise and of y and 1 to x. – qaphla Aug 9 '13 at 6:09

$\frac{|x|}{x}$ where $x \ne 0$.

Why not something like

if(x<0) y=-1; else y=+1?

With some appropriate way to handle x=0?

• trying to squeeze performance if possible. But it all maybe pointless...:D – Muhammad Umer Aug 9 '13 at 6:18
• If all you want is the sign function, not the absolute value, an even faster way to do that would be sign(x) = (-2) * (x & 0x80000000) + 1, though this again relies on using bitwise and, and on being sure of the representation of your number. – qaphla Aug 9 '13 at 6:21