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.


if x=2 
if x=-3435

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).

  • $\begingroup$ i couldn't find tag suitable $\endgroup$ – Muhammad Umer Aug 9 '13 at 5:10
  • $\begingroup$ 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. $\endgroup$ – 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


  • $\begingroup$ check my comment thanks... $\endgroup$ – Muhammad Umer Aug 9 '13 at 5:34
  • $\begingroup$ @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. $\endgroup$ – user61527 Aug 9 '13 at 5:35
  • $\begingroup$ 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..) $\endgroup$ – Muhammad Umer Aug 9 '13 at 5:38
  • $\begingroup$ You could also use $|x| = \sqrt{x^2}$, but this will likely increase execution time if it's called a lot. $\endgroup$ – user61527 Aug 9 '13 at 5:39
  • 1
    $\begingroup$ 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. $\endgroup$ – 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?

  • $\begingroup$ trying to squeeze performance if possible. But it all maybe pointless...:D $\endgroup$ – Muhammad Umer Aug 9 '13 at 6:18
  • $\begingroup$ 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. $\endgroup$ – qaphla Aug 9 '13 at 6:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.