Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question

closed as unclear what you're asking by Peter Taylor, xnor, VTCAKAVSMoACE, Doorknob Dec 14 '15 at 12:16

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

    
Is the program allowed to loop forever and continue receiving input, finding the absolute value, and outputting it? – Justin Dec 7 '13 at 0:59
2  
@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. – Timtech Dec 9 '13 at 15:50
3  
@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 – Doorknob Dec 9 '13 at 17:57
7  
-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. – Gareth Dec 11 '13 at 20:15
4  
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 – Peter Taylor Dec 14 '15 at 11:34

49 Answers 49

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

share|improve this answer
3  
If you write it as (%*) you also get complex magnitude for no extra characters. – FireFly Dec 7 '13 at 11:15
2  
Wouldn't this be considered a built-in sgn function? – LegionMammal978 Dec 4 '15 at 12:13

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
share|improve this answer
    
Try writing a version that does support floating point (like my Befunge version now does) – Justin Dec 7 '13 at 0:56
1  
@Quincunx Challenge accepted ;) after I get back to a computer; commenting from a phone right now – Doorknob Dec 7 '13 at 1:24
    
@Quincunx Done, 4 characters :) – Doorknob Dec 7 '13 at 1:50
1  
@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 – Doorknob Dec 7 '13 at 14:54
1  
@musefan Shall we start discussing that / is not a function but an operator??? – Howard Dec 9 '13 at 17:04

Perl: 5 characters

s/-//

The example:

perl -e '$_=-82.923; s/-//; print' # will print 82.923 or return it unless use 'print'
share|improve this answer
    
This is a good sed answer, too. – Toby Speight Dec 1 '15 at 17:40

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.

share|improve this answer
9  
It needs parentheses around the -a, otherwise it expands to --a. – Paul R Dec 8 '13 at 11:06

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
share|improve this answer

Brainfuck, 40 chars

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

Or 35 chars if wrapping is allowed.

-[+>+[+<]>+],+[->->+<<]>[>-.>],[.,]
share|improve this answer

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.

share|improve this answer
    
×× should be enough, as per this J answer. – Adám Dec 6 '15 at 18:39

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))
share|improve this answer
    
Yes, abs is not permitted – Timtech Dec 8 '13 at 22:48
    
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. – MartinM Dec 8 '13 at 23:37
    
It's just that so many people are... but have an upvote :) – Timtech Dec 9 '13 at 11:48
    
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. – Justin Dec 9 '13 at 17:56
    
@Quincunx Splitting a string is a function – Timtech Dec 10 '13 at 22:27

Python CLI, 20

lambda x:[x,-x][x<0]
share|improve this answer
    
"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. – Justin Dec 7 '13 at 19:23
    
Yes, this doesn't count. It has to take input and return or output. – Timtech Dec 7 '13 at 21:46
    
@Quincunx fixed – boothby Dec 8 '13 at 14:50
    
Needs minor adjustment. (lambda x:[x,-x][x>0])(42) returns -42. – manatwork Dec 8 '13 at 14:57
2  
This isn't reusable though, should you include something like g= before it? Or is this really ok? – Justin Dec 9 '13 at 0:24

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

share|improve this answer
1  
5 chars: √#^2& – chyaong Dec 7 '13 at 14:57
    
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. – DavidC Dec 7 '13 at 16:44
2  
What about ? – FireFly Dec 7 '13 at 19:05
    
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. – DavidC Dec 7 '13 at 21:04
    
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 ⁻ ⁺ ⁽ ⁾ ⁼. – FireFly Dec 7 '13 at 21:29

Haskell, 14 characters

sqrt.flip(^)2$
share|improve this answer

J, 13

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

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

f -1.253
1.253
f 0.91235
0.91235
share|improve this answer

Python 2.7 (16 charcters)

This one is the shortest here in python.

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

Let n = input(), then equation

share|improve this answer
    
+1, definitely a great answer. Wouldn't **.5 work though? – Timtech Dec 26 '13 at 23:45
    
@Timtech Yes, I didn't think of that. Thanks. BTW This is my first answer here. – Kartik Dec 27 '13 at 4:06

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
share|improve this answer
    
Maybe edit this into your other answer instead? (I'll undownvote it if you do) – lirtosiast Nov 29 '15 at 20:31
    
@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. – Timtech Dec 1 '15 at 23:15
    
There's also Anscos(angle(Ans at 5 bytes, which is interesting. – lirtosiast Dec 1 '15 at 23:36
    
Thanks for that suggestion - it's smart since cos(x) = cos(-x) – Timtech Dec 2 '15 at 0:26
    
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. – lirtosiast Dec 2 '15 at 1:18

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.

share|improve this answer

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

share|improve this answer
    
Nice one - clears the sign bit. But the question requires numbers between -9E99 and 9E99 - you need double. – ugoren Feb 24 '14 at 10:02
    
@urogen — unverified: *(long*)&f&=LONG_MAX; where f is a double. – moala Dec 2 '15 at 12:49

EXCEL, 10:

=SQRT(n^2)

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

share|improve this answer
    
+1 for using the square to think outside the box ;) – WallyWest Nov 27 '14 at 3:27
    
Is using SQRT() really ok with the rules? – yeti Nov 28 '15 at 21:18
    
@yeti - it's listed in the question... – Toby Speight Dec 1 '15 at 17:45
    
Ok... maybe I just was too tired to get my eyes open wide enough... :-\ – yeti Dec 1 '15 at 17:49

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

share|improve this answer
2  
You don't need a=. – Mama Fun Roll Nov 29 '15 at 17:18

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

share|improve this answer
1  
is shorter than 21/. – Mego Nov 28 '15 at 20:13
1  
Also try it online. – Mego Nov 28 '15 at 20:14
1  
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. – quintopia Dec 25 '15 at 17:25

Java - 36

This is the obvious solution.

double a(double b){return b<0?-b:b;}
share|improve this answer
    
Is the semicolon required? I do more JavaScript than Java. – Timtech Dec 6 '13 at 23:48
    
@Timtech Yes. Every Java statement, apart from code blocks, needs a semicolon – Justin Dec 6 '13 at 23:55

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

share|improve this answer

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

share|improve this answer
    
I'm sorry, but the program has to be able to accept any real number as input. – Timtech Dec 6 '13 at 23:37
    
@Timtech Well, if the programming language is not capable of that, then... – Doorknob Dec 6 '13 at 23:38
    
@Doorknob It happens. Learning multiple programming languages may be the way to go. – Timtech Dec 6 '13 at 23:45
    
@Timtech notice that I have three answers in different languages... – Justin Dec 6 '13 at 23:46
1  
: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). – FireFly Dec 7 '13 at 11:47

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)- +)%)
share|improve this answer
    
I'm sorry, max is not allowed. No hard feelings, I am not supportive of all the answers that break the rules. – Timtech Dec 15 '13 at 23:56
1  
@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. – Justin Dec 16 '13 at 0:35
1  
@Timtech Here is another definition: physicsforums.com/showthread.php?t=337952 – Justin Dec 16 '13 at 0:41
    
@Quincunx I understand that it can be defined mathematically, and I am fine with that. – Timtech Dec 16 '13 at 11:38

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.

share|improve this answer

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.

share|improve this answer
    
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 :). – mroman Dec 2 '15 at 9:19

Rotor, 2 bytes

sS

Challenge predates this language by two years, so this isn't competitive.

Squares input and then square roots it. Nothing special.

share|improve this answer

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
share|improve this answer

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>
share|improve this answer

PHP, 30

<?=($n=$argv[1])*(1-($n<0)*2);
share|improve this answer

Gema, 2 characters

Same as edem's Perl answer.

-=

Sample run:

bash-4.3$ gema -p '-=' <<< '-82.923'
82.923
share|improve this answer

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