5
\$\begingroup\$

The challenge is to take any real number as input and output or return the absolute value. You may not use any built-in functions other than those dealing with input and output/returning. This is code golf, so the shortest code wins. This is my first question here, so bear with me if I've left something obvious out of the challenge.

As per Quincunx's suggestion, I am limiting input to anywhere between -9E99 and 9E99.

Also, the only functions/operators you can use are input, output, return, +, -, *, /, %, ^ +=, -=, *=, /=, >, <, ==, >=, <=, !=, square, and square root or their equivalents

\$\endgroup\$
20
  • 3
    \$\begingroup\$ @Timtech: Can you clarify "You may not use any built-in functions"? For example, does the GolfScript answer violate this rule when it uses the built-in split functions? Or did you just mean built-in functions that are specifically designed to calculate the absolute value? \$\endgroup\$
    – musefan
    Dec 9, 2013 at 14:08
  • 2
    \$\begingroup\$ @musefan You may not use any built in functions (math operators are not included, they are not functions). The GolfScript answer did violate the rule; that's why it's not accepted. \$\endgroup\$
    – Timtech
    Dec 9, 2013 at 15:50
  • 4
    \$\begingroup\$ @tim Why don't operators count as functions? In C and friends you can override operators and use them just like normal functions. This seems to be a very vague rule \$\endgroup\$
    – Doorknob
    Dec 9, 2013 at 17:57
  • 9
    \$\begingroup\$ -1. Question is vague and the definition of "built-in function" has only appeared in the comments 3 days after the question was posed. It seems like you're just looking for the shortest way to say printf(x*(x<0?-1:1)) in a number of languages. \$\endgroup\$
    – Gareth
    Dec 11, 2013 at 20:15
  • 5
    \$\begingroup\$ Apart from the fact that the question as currently written seems to permit a whitelist of operators but only if they're not built in to the language, this is a classic example of why trying to whitelist permitted operations is a disaster. Consider >: in some languages it returns 0 or 1; in other languages it returns true or false and Booleans can't be cast to integers. Should languages in the second category be permitted to use ?: in contexts which could be algebraically rewritten in terms of the condition as 0 or 1 under the "or their equivalents" grant? It's extremely fuzzy \$\endgroup\$ Dec 14, 2015 at 11:34

49 Answers 49

21
\$\begingroup\$

J, 2 bytes

**

Usage:

   f =: **
   f 9.3
9.3
   f -9.3
9.3

Explanation:

This uses the * verb in both its monadic and dyadic forms. The monadic form returns -1 if it's given a negative number, 0 if it's given 0 and 1 if it's given a positive number. The dyadic form is just plain old multiplication. Putting them in a function literal turns them into a hook which gets evaluated like this: y * (*y).

\$\endgroup\$
2
  • 4
    \$\begingroup\$ If you write it as (%*) you also get complex magnitude for no extra characters. \$\endgroup\$
    – FireFly
    Dec 7, 2013 at 11:15
  • 2
    \$\begingroup\$ Wouldn't this be considered a built-in sgn function? \$\endgroup\$ Dec 4, 2015 at 12:13
15
\$\begingroup\$

GolfScript, 4 characters

I believe I win. ;)

Works with integer or decimal numbers of any length.

'-'/

Try it online

These programs do the same and are of equal length:

'-'-
'-'%

GolfScript (old version), 16 13

My first GS program! (that actually does something)

Doesn't work with decimal numbers because GolfScript doesn't have floating point.

~:$0<{0$-}$if
\$\endgroup\$
18
  • \$\begingroup\$ Try writing a version that does support floating point (like my Befunge version now does) \$\endgroup\$
    – Justin
    Dec 7, 2013 at 0:56
  • 1
    \$\begingroup\$ @Quincunx Challenge accepted ;) after I get back to a computer; commenting from a phone right now \$\endgroup\$
    – Doorknob
    Dec 7, 2013 at 1:24
  • \$\begingroup\$ @Quincunx Done, 4 characters :) \$\endgroup\$
    – Doorknob
    Dec 7, 2013 at 1:50
  • 1
    \$\begingroup\$ @peter Why is this cheating? Also, if you use % instead of / the empty string will be removed, but it doesn't matter since the output is the same \$\endgroup\$
    – Doorknob
    Dec 7, 2013 at 14:54
  • 1
    \$\begingroup\$ @musefan Shall we start discussing that / is not a function but an operator??? \$\endgroup\$
    – Howard
    Dec 9, 2013 at 17:04
6
\$\begingroup\$

Perl: 5 characters

s/-//

The example:

perl -e '$_=-82.923; s/-//; print' # will print 82.923 or return it unless use 'print'
\$\endgroup\$
1
  • \$\begingroup\$ This is a good sed answer, too. \$\endgroup\$ Dec 1, 2015 at 17:40
5
\$\begingroup\$

C - 21

#define x(a) a<0?-a:a

This is a preprocessor macro, but does the same thing as Quincunx's Java solution when a real number is used as input.

\$\endgroup\$
1
  • 9
    \$\begingroup\$ It needs parentheses around the -a, otherwise it expands to --a. \$\endgroup\$
    – Paul R
    Dec 8, 2013 at 11:06
5
\$\begingroup\$

J - 7 3

Max of number and inverse (3)

>.-

When assigned to a function: take the maximum between the negative and the number, using a hook so: (f g) y = y f g y

f=:>.-
f _4 5 _1 0
   4 5 1 0

root of the square (5 or 4)

]&.*: _4 5 _1 0
    4 5 1 0
NB. or if an expression is good enough:
%:*: _4 5 _1 0
    4 5 1 0

Negate if number smaller than its negative (7)

-^:(<-) 

Takes the inverse (the inverse is bigger than the number itself) times.

Would loosely translate to:

if -num > num then
    num= -num
end
\$\endgroup\$
4
\$\begingroup\$

Brainfuck, 40 chars

+++++[>+++++++++<-],[->->+<<]>[>.>],[.,]

Or 35 chars if wrapping is allowed.

-[+>+[+<]>+],+[->->+<<]>[>-.>],[.,]
\$\endgroup\$
4
\$\begingroup\$

Mathematica 10 8

Method 1 (8 chars)

Take the square root of a number squared.

Sqrt@#²&

Examples

Sqrt@#²&[-.0176987]
Sqrt@#²&[.0176987]

.0176987
.0176987


Method 2 (8 chars)

Sign returns -1 if negative, 0 if zero, 1 if positive.

# Sign@#&

Examples

# Sign@#&[-4.3]
# Sign@#&[4.3]

4.3
4.3


4 chars?

As the following picture shows, it is possible to legitimately reduce the function, but I haven't been able to replicate the input on SO.

abs value

\$\endgroup\$
6
  • 1
    \$\begingroup\$ 5 chars: √#^2& \$\endgroup\$
    – chyanog
    Dec 7, 2013 at 14:57
  • \$\begingroup\$ I was trying that but I couldn't get a rendering of the square root symbol as it would actually be used in Mathematica (it would actually contain the #^2.) #^2 should be possible to show with two symbols, but I couldn't find a way to show that either. \$\endgroup\$
    – DavidC
    Dec 7, 2013 at 16:44
  • 2
    \$\begingroup\$ What about ? \$\endgroup\$
    – FireFly
    Dec 7, 2013 at 19:05
  • \$\begingroup\$ Thanks! That works. How did you manage to generate it? (I copied and pasted your example.) Btw, I've tried pasting Latex and MathML code for the square root, with no success. \$\endgroup\$
    – DavidC
    Dec 7, 2013 at 21:04
  • \$\begingroup\$ Dead caret followed by 2 yields ² for me (on Linux using xkb and a keyboard layout that happens to use dead-key variants for ^ ~ ¨ etc). Same goes for other digits and ⁻ ⁺ ⁽ ⁾ ⁼. \$\endgroup\$
    – FireFly
    Dec 7, 2013 at 21:29
4
\$\begingroup\$

APL, 5

×∘×⍨⎕

A function would be 4 chars

×∘×⍨

Explanation

×, when used with one argument, is the signum function; when used with two arguments, is multiplication.
is the compose(combination) of two functions.

×∘× is a function that takes two arguments and return the left argument times the signum of the right arugment.
means "use right argument as both left and right argument".
takes input from screen.

\$\endgroup\$
1
  • \$\begingroup\$ ×× should be enough, as per this J answer. \$\endgroup\$
    – Adám
    Dec 6, 2015 at 18:39
4
\$\begingroup\$

C: 13 characters

I would assume using overloaded operators are not permitted? Just because something is abstracted and doesn't follow the standard formatting of a function call doesn't mean it isn't a function.

For example: (**)n <==> abs(n) <==> '-'/

Anyways, here is my code: With explanation:

n+: ==> +(true - false) ==> +(1-0) ==> +1

n-: ==> -(false - true) ==> -(0-1) ==> -(-1) ==> +1

a=n*(n>0 - (n<0))
\$\endgroup\$
5
  • \$\begingroup\$ Yes, abs is not permitted \$\endgroup\$
    – Timtech
    Dec 8, 2013 at 22:48
  • \$\begingroup\$ I understand that. That is why I don't believe the people posting overloaded operands should be permitted either. Since those are functions, just without the typical wrapping. \$\endgroup\$
    – MartinM
    Dec 8, 2013 at 23:37
  • \$\begingroup\$ It's just that so many people are... but have an upvote :) \$\endgroup\$
    – Timtech
    Dec 9, 2013 at 11:48
  • \$\begingroup\$ How is '-'/ an overloaded operand? It just takes a String, splits it on the - character (removing such characters from the output), then prints it. This is definitely not equivalent to abs(n) (as your <==> (iff) suggests. \$\endgroup\$
    – Justin
    Dec 9, 2013 at 17:56
  • \$\begingroup\$ @Quincunx Splitting a string is a function \$\endgroup\$
    – Timtech
    Dec 10, 2013 at 22:27
4
\$\begingroup\$

Python CLI, 20

lambda x:[x,-x][x<0]
\$\endgroup\$
7
  • \$\begingroup\$ "output or return the absolute value". Doesn't that imply that this needs to be in a method? Otherwise, some of my code can be vastly shortened. \$\endgroup\$
    – Justin
    Dec 7, 2013 at 19:23
  • \$\begingroup\$ Yes, this doesn't count. It has to take input and return or output. \$\endgroup\$
    – Timtech
    Dec 7, 2013 at 21:46
  • \$\begingroup\$ @Quincunx fixed \$\endgroup\$
    – boothby
    Dec 8, 2013 at 14:50
  • \$\begingroup\$ Needs minor adjustment. (lambda x:[x,-x][x>0])(42) returns -42. \$\endgroup\$
    – manatwork
    Dec 8, 2013 at 14:57
  • 2
    \$\begingroup\$ This isn't reusable though, should you include something like g= before it? Or is this really ok? \$\endgroup\$
    – Justin
    Dec 9, 2013 at 0:24
3
\$\begingroup\$

Haskell, 14 characters

sqrt.flip(^)2$
\$\endgroup\$
3
\$\begingroup\$

J, 13

Without using build-in functions (like signum and the like):

f =: -`]@.(0&<)

f -1.253
1.253
f 0.91235
0.91235
\$\endgroup\$
3
\$\begingroup\$

Python 2.7 (16 charcters)

This one is the shortest here in python.

(input()**2)**.5

Let n = input(), then equation

\$\endgroup\$
2
  • \$\begingroup\$ +1, definitely a great answer. Wouldn't **.5 work though? \$\endgroup\$
    – Timtech
    Dec 26, 2013 at 23:45
  • \$\begingroup\$ @Timtech Yes, I didn't think of that. Thanks. BTW This is my first answer here. \$\endgroup\$
    – Kartik
    Dec 27, 2013 at 4:06
3
\$\begingroup\$

EXCEL, 10:

=SQRT(n^2)

-- n is a defined cell name with the input value.

\$\endgroup\$
4
  • \$\begingroup\$ Is using SQRT() really ok with the rules? \$\endgroup\$
    – user19214
    Nov 28, 2015 at 21:18
  • \$\begingroup\$ @yeti - it's listed in the question... \$\endgroup\$ Dec 1, 2015 at 17:45
  • \$\begingroup\$ Ok... maybe I just was too tired to get my eyes open wide enough... :-\ \$\endgroup\$
    – user19214
    Dec 1, 2015 at 17:49
  • \$\begingroup\$ VBA version of this, 12 bytes ?([A1]^2)^.5 \$\endgroup\$ Mar 25, 2017 at 20:00
3
\$\begingroup\$

TI-Basic, 3 bytes

Outputs square root of input squared.

√(Ans²

Alternates

√(AnsAns          3 bytes
Ans²^.5           5 bytes
max(Ans,-Ans      5 bytes
Anscos(angle(Ans  5 bytes
-min(Ans,-Ans     6 bytes
If Ans<0:-Ans     7 bytes
Ans-2Ans(Ans<0    8 bytes
Ans(2(Ans>0)-1    10 bytes
Ans(-1+2(Ans>0    10 bytes
\$\endgroup\$
6
  • \$\begingroup\$ Maybe edit this into your other answer instead? (I'll undownvote it if you do) \$\endgroup\$
    – lirtosiast
    Nov 29, 2015 at 20:31
  • \$\begingroup\$ @ThomasKwa Didn't notice that other answer (that was a while ago), thanks for the notice, I'll delete it and add a better version as an alternate here. \$\endgroup\$
    – Timtech
    Dec 1, 2015 at 23:15
  • \$\begingroup\$ There's also Anscos(angle(Ans at 5 bytes, which is interesting. \$\endgroup\$
    – lirtosiast
    Dec 1, 2015 at 23:36
  • \$\begingroup\$ Thanks for that suggestion - it's smart since cos(x) = cos(-x) \$\endgroup\$
    – Timtech
    Dec 2, 2015 at 0:26
  • \$\begingroup\$ That's not how Anscos(angle(Ans works. angle( returns pi for negative numbers and 0 for nonnegative numbers. cos( returns -1 for pi and 1 for 0. Therefore, you're multiplying the number by its sign function, except for 0 which doesn't matter. \$\endgroup\$
    – lirtosiast
    Dec 2, 2015 at 1:18
2
\$\begingroup\$

Python - 31 28 26 24 23 18

Uses boothby's idea of a lambda function, saving 5 characters (or 3 if I need to assign it to a variable):

lambda x:(x*x)**.5

Old Methods

Uses a generator function to save 1 char, so it is necessary to print the value with some function that uses a generator/iterator, like for i in a(b):print(i)

def a(b):yield(b*b)**.5

Saved 2 3 characters by squaring and unsquaring.


def a(b):yield(b<0)*-2*b+b

Old one:

def a(b):yield b if b>0 else-b

Edit: saved two characters by factoring b in.

\$\endgroup\$
2
\$\begingroup\$

C, 19

Slightly more than some other C answers, but guaranteed branch-less. the f variable is a float. I hope the bitwise operator & is allowed.

*(int*)&f&=INT_MAX;

Inspired from http://devmaster.net/posts/9998/the-ultimate-fast-absolute-value

\$\endgroup\$
2
  • \$\begingroup\$ Nice one - clears the sign bit. But the question requires numbers between -9E99 and 9E99 - you need double. \$\endgroup\$
    – ugoren
    Feb 24, 2014 at 10:02
  • \$\begingroup\$ @urogen — unverified: *(long*)&f&=LONG_MAX; where f is a double. \$\endgroup\$
    – moala
    Dec 2, 2015 at 12:49
2
\$\begingroup\$

JavaScript 26 13

alert((b=prompt())<0?-b:b)

Reducing it further with fat arrow functions...

a=b=>b<0?-b:b

Et voila! Reduction by 50%! Only issue is that this now only works for Firefox 22 and above with thanks to the fat arrows...

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You don't need a=. \$\endgroup\$ Nov 29, 2015 at 17:18
2
\$\begingroup\$

Seriously, 8 7 4 3 bytes

Thanks @quintopia

My first Seriously answer, to a 2 yr old question!

Note the challenge is older than the language

,ª√

Seriously is a stack based language. What this does is it pushes the input on the stack, then multiplies if with itself. Then it takes the square root of the result. It is based on the fact that sqrt(x^2)=|x|.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ is shorter than 21/. \$\endgroup\$
    – user45941
    Nov 28, 2015 at 20:13
  • 1
    \$\begingroup\$ Also try it online. \$\endgroup\$
    – user45941
    Nov 28, 2015 at 20:14
  • 1
    \$\begingroup\$ Put the 1/2 at the beginning of the program and you can avoid stack rotation. Also, since the question says square and square root are allowed, you can do this in 3 bytes by using those two commands. \$\endgroup\$
    – quintopia
    Dec 25, 2015 at 17:25
1
\$\begingroup\$

Java - 36

This is the obvious solution.

double a(double b){return b<0?-b:b;}
\$\endgroup\$
2
  • \$\begingroup\$ Is the semicolon required? I do more JavaScript than Java. \$\endgroup\$
    – Timtech
    Dec 6, 2013 at 23:48
  • \$\begingroup\$ @Timtech Yes. Every Java statement, apart from code blocks, needs a semicolon \$\endgroup\$
    – Justin
    Dec 6, 2013 at 23:55
1
\$\begingroup\$

Ruby, 15 characters

a=->b{b>0?b:-b}

Ruby, 22 chars (with I/O)

p (a=gets.to_f)>0?a:-a

Accepts input on stdin, outputs on stdout

\$\endgroup\$
1
\$\begingroup\$

Befunge 98 - 11 7 8

~:'-`!j,

Explained:

~  read character input
:  duplicate
'- fetch - and push it
`  compare duplicated value with it, 1 if first is greater, otherwise 0
!  if the number on the stack is 0, set it to 1, otherwise 0
j  jump the number of characters on the top of the stack, which is 1 if the input character is -
,  print the character on top of the stack

If I understand this correctly, then this works for any input, but only if constant looping is allowed. It simply prints everything but the minus sign. If infinite looping is not allowed, then this should work (13 10 chars (Thanks FireFly)):

~:'-`!j,#@

Old version (Befunge 93) - 11

&:0`2*1-*.@

It works like this:

& push input
: push a duplicate
0 push a zero
` pop duplicate and 0, if duplicate greater than 0, push 1 else 0
2 push a two
* pop the 1 or 0 and 2 , multiply the 1 or 0 by the 2
1 push a one
- pop last two values and subtract the second value on the stack by the first (ie a-1)
* pop last two values and multiply last two values on stack (ie + or - 1 * input)
. print
@ end program

Note: Only integers are valid numbers in Befunge.


If I need to support floating point input, then it is 18 chars:

&&\:0`2*1-*.".",.@

It is 17 chars in Befunge 98:

&&\:0`2*1-*.'.,.@

Note: these print a space before the decimal point

\$\endgroup\$
10
  • \$\begingroup\$ I'm sorry, but the program has to be able to accept any real number as input. \$\endgroup\$
    – Timtech
    Dec 6, 2013 at 23:37
  • \$\begingroup\$ @Timtech Well, if the programming language is not capable of that, then... \$\endgroup\$
    – Doorknob
    Dec 6, 2013 at 23:38
  • \$\begingroup\$ @Doorknob It happens. Learning multiple programming languages may be the way to go. \$\endgroup\$
    – Timtech
    Dec 6, 2013 at 23:45
  • \$\begingroup\$ @Timtech notice that I have three answers in different languages... \$\endgroup\$
    – Justin
    Dec 6, 2013 at 23:46
  • 1
    \$\begingroup\$ :O I had no clue ' fetch character existed. Oh, and you need ot negate the greater-than I believe. Also, for the non-infinite-looping version, ~.'-backtick!j,#@ works (~ acts as a reflector on EOF in B98). \$\endgroup\$
    – FireFly
    Dec 7, 2013 at 11:47
1
\$\begingroup\$

Clojure 13 18 chars

#(max %(- %))

i am not sure if max is allowed, but i have seen others use it so here it goes :)

after the debate in the comments below, it was decided that max is indeed allowed!

use it like that:

(#(max %(- %)) -2) ; returns 2

edit - it seems max isnt allowed, so lets resort to the trivial solution

a trivial solution:

#(if(< % 0)(- %)%)

or

#((if(< % 0)- +)%)
\$\endgroup\$
4
  • \$\begingroup\$ I'm sorry, max is not allowed. No hard feelings, I am not supportive of all the answers that break the rules. \$\endgroup\$
    – Timtech
    Dec 15, 2013 at 23:56
  • 1
    \$\begingroup\$ @Timtech max can easily be defined mathematically: max(x,y) = if x < y then y, otherwise if x not < y then x (or in a set: {((x,y),z)|if x > y, z = x or if x not > y, z = y}). This is a function from reals to the reals. As such, I would say that max is allowed, for the same reason that sqrt is. \$\endgroup\$
    – Justin
    Dec 16, 2013 at 0:35
  • 1
    \$\begingroup\$ @Timtech Here is another definition: physicsforums.com/showthread.php?t=337952 \$\endgroup\$
    – Justin
    Dec 16, 2013 at 0:41
  • \$\begingroup\$ @Quincunx I understand that it can be defined mathematically, and I am fine with that. \$\endgroup\$
    – Timtech
    Dec 16, 2013 at 11:38
1
\$\begingroup\$

C# 6.0, 29 bytes

double m(double n)=>n<0?-n:n;
\$\endgroup\$
2
  • \$\begingroup\$ Note that this uses a feature of C# 6 (designed some time after the challenge was posted). \$\endgroup\$ Nov 29, 2015 at 15:24
  • \$\begingroup\$ @VisualMelon Included C# 6.0 note there. \$\endgroup\$
    – Yytsi
    Nov 29, 2015 at 15:27
1
\$\begingroup\$

MATLAB, 10 bytes

@(a)a^2^.5

Pretty straight forward. We are allowed sqauare and square root, so the absolute value of a number (assuming it is not complex!) is simply square it then square root it.

\$\endgroup\$
1
\$\begingroup\$

Burlesque, 4 bytes

XXim

XX returns the digits of an integer and im converts the digits back to an integer. XX removes the sign.

You might also go with Jsn?* depending on the exact types.

\$\endgroup\$
1
  • \$\begingroup\$ If the integer given does not contain any duplicate digits then you can use NB. See, that's what makes golfing fun. Exploiting every trick to pass testcases :). \$\endgroup\$
    – mroman
    Dec 2, 2015 at 9:19
1
\$\begingroup\$

Prolog, 22 bytes

Saves 7 bytes over printing as we were allowed to return the absolute value.

Code:

p(X,Y):-Y is(X^2)^0.5.

Explanation:

Input X is squared, taken the root of and returned as Y.

Example:

p(-9.0e99,X).
X = 9.0e+99
\$\endgroup\$
1
\$\begingroup\$

Milky Way 1.1.5, 13 bytes

':0e?{_^_;-}!

Explanation

'              # read input from the command line
 :             # push a duplicate of the TOS to the stack
  0            # push 0 to the stack
   e           # push the truth value of A > B where A and B are the top two stack elements
    ?{_ _  }   # if-else statement
       ^       # pop the TOS without outputting
         ;     # swap the top two stack elements
          -    # push the value of A - B where A and B are the top two stack elements
            !  # output the TOS

Usage

./mw <path-to-code> -i <input-integer>
\$\endgroup\$
1
\$\begingroup\$

PHP, 30

<?=($n=$argv[1])*(1-($n<0)*2);
\$\endgroup\$
1
\$\begingroup\$

Gema, 2 characters

Same as edem's Perl answer.

-=

Sample run:

bash-4.3$ gema -p '-=' <<< '-82.923'
82.923
\$\endgroup\$

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