5

How do I get the absolute value of a number without using math.abs?

This is what I have so far:

function absVal(integer) {
    var abs = integer * integer;
    return abs^2;
}
Satpal
  • 132,252
  • 13
  • 159
  • 168
chaneyz
  • 95
  • 1
  • 1
  • 6

6 Answers6

10

You can use the conditional operator and the unary negation operator:

function absVal(integer) {
  return integer < 0 ? -integer : integer;
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
5

You can also use >> (Sign-propagating right shift)

function absVal(integer) {
    return (integer ^ (integer >> 31)) - (integer >> 31);;
}

Note: this will work only with integer

Satpal
  • 132,252
  • 13
  • 159
  • 168
3

Since the absolute value of a number is "how far the number is from zero", a negative number can just be "flipped" positive (if you excuse my lack of mathematical terminology =P):

var abs = (integer < 0) ? (integer * -1) : integer;

Alternatively, though I haven't benchmarked it, it may be faster to subtract-from-zero instead of multiplying (i.e. 0 - integer).

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
  • I'd be shocked if subtracting from 0 is slower than an if statement – taylorc93 May 15 '15 at 21:17
  • @taylorc93 No, no - not in place of the entire ternary statement, in place of the `(integer * -1)` portion... I probably should've written that one all the way out =P – newfurniturey May 15 '15 at 21:17
  • Ahhhh, that makes more sense now. Yeah, that would be worth benchmarking but unless this code is being run millions of times in the program, I don't think it would make too much of a difference – taylorc93 May 15 '15 at 21:20
2

Late response, but I think this is what you were trying to accomplish:

function absVal(integer) {
   return (integer**2)**.5;
}

It squares the integer then takes the square root. It will eliminate the negative.

Tony
  • 2,658
  • 2
  • 31
  • 46
0

Check if the number is less than zero! If it is then mulitply it with -1;

user4655509
  • 81
  • 1
  • 8
-1

There's no reason why we can't borrow Java's implementation.

    function myabs(a) {
      return (a <= 0.0) ? 0.0 - a : a;
    }

    console.log(myabs(-9));

How this works:

  • if the given number is less than or zero
    • subtract the number from 0, which the result will always be > 0
  • else return the number (because it's > 0)
jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • This is not a good solution: this function performs a substraction if a equals zero, but 0.0-0.0 is already 0.0 so `(a <0.0)` is better. Secondly, there is no substraction needed because there is the unary negate operator. – Paebbels May 15 '15 at 21:38
  • 1
    Thank you for your feedback. My overarching point was addressing that if you have a well-solved problem you need to implement, look at other known working solutions and use that. – jdphenix May 15 '15 at 21:42
  • 1
    That's a good point, but Java's way seems not to be the best :) – Paebbels May 15 '15 at 21:44