Sign up ×
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.

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. Also, single-characters math operators are allowed (+, -, *, /, %, ^)

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
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
take any real number as input. I believe that no program can do this. Most solutions here won't work for -10^-googol for instance. Maybe you should restrict it to double values or something similar. But the what about -π? Programs that only allow doubles wouldn't work. Also, what about something like π-4? – Justin Dec 7 '13 at 5:47
@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
@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
-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

44 Answers 44

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.

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
@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
@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
@musefan Shall we start discussing that / is not a function but an operator??? – Howard Dec 9 '13 at 17:04

J, 2 bytes



   f =: **
   f 9.3
   f -9.3


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
If you write it as (%*) you also get complex magnitude for no extra characters. – FireFly Dec 7 '13 at 11:15

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
It needs parentheses around the -a, otherwise it expands to --a. – Paul R Dec 8 '13 at 11:06

Perl: 5 characters


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 11 hours ago

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

APL, 5


A function would be 4 chars



×, 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

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

Brainfuck, 40 chars


Or 35 chars if wrapping is allowed.

share|improve this answer

Mathematica 10 8

Method 1 (8 chars)

Take the square root of a number squared.





Method 2 (8 chars)

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

# Sign@#&


# Sign@#&[-4.3]
# Sign@#&[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
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. – David Carraher Dec 7 '13 at 16:44
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. – David Carraher 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

J, 13

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

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

f -1.253
f 0.91235
share|improve this answer

Python 2.7 (16 charcters)

This one is the shortest here in python.


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.



√(AnsAns          3 bytes
Ans²^.5           5 bytes
Anscos(angle(Ans  5 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) – Thomas Kwa 2 days ago
@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 5 hours ago
There's also Anscos(angle(Ans at 5 bytes, which is interesting. – Thomas Kwa 5 hours ago
Thanks for that suggestion - it's smart since cos(x) = cos(-x) – Timtech 4 hours ago
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. – Thomas Kwa 3 hours ago

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.


Inspired from

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

EXCEL, 10:


-- 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 at 21:18
@yeti - it's listed in the question... – Toby Speight 11 hours ago
Ok... maybe I just was too tired to get my eyes open wide enough... :-\ – yeti 11 hours ago

JavaScript 26 13


Reducing it further with fat arrow functions...


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
You don't need a=. – ןnɟuɐɯɹɐןoɯ 2 days ago

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


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



~  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)):


Old version (Befunge 93) - 11


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:


It is 17 chars in Befunge 98:


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

Haskell, 14 characters

share|improve this answer

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)(- %)%)


#((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
@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
@Timtech Here is another definition: – 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

Seriously, 8 7 bytes

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


Seriously is a stack based language. What this does is it pushes 2 on the stack, then the input, then the power of the input with the 2 already on the stack. Then it pushes 1/2 on the stack (that is the "1½") and it finally rotates the stack and takes the power. It is based on the fact that sqrt(x^2)=|x|.

share|improve this answer
is shorter than 21/. – Mego Nov 28 at 20:13
Also try it online. – Mego Nov 28 at 20:14

MATLAB, 10 bytes


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

𝔼𝕊𝕄𝕚𝕟, 5 bytes (noncompetitive)

√ ï²⦆

Try it here (Firefox only).

I'm trying out a custom single-byte encoding (called Mines) that tries to cure 𝔼𝕊𝕄𝕚𝕟's inherently disproportionate byte-to-char ratios.

share|improve this answer
It's really annoying not being able to see the name of the language. Can you just use "ESMin" instead? – mbomb007 6 hours ago
Sorry no. The language name is in doublestruck, and will continue to do so forever and ever. – ןnɟuɐɯɹɐןoɯ 5 hours ago

Burlesque, 4 bytes


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

PowerShell: 38

Lazy if/else. Maybe I'll find a shorter way later.

share|improve this answer

R 17 characters


Or 13 characters by adapting David Carraher Mathematica answer:

share|improve this answer
Max isn't allowed; I'd recommend switching to your 13 character solution. – Timtech Dec 24 '13 at 14:45

Ti-84 Table, 12 5 characters

The text in brackets are the square root character and the squared character, respectively.

Y=[square root]X[^2]

The old code:


Both of these handle rational and irrational numbers. Any real number is valid, with limits of -9.99999999*10^99 and 9.99999999*10^99 for the second one and sqrt(-9.99999999*10^99) and sqrt(9.99999999*10^99) for the first one.

Gets input on X and shows equivalent absolute number as Y.

share|improve this answer
Square root is a function. – Gareth Dec 11 '13 at 20:19
@Gareth It's dealing with mathematics. – Timtech Dec 11 '13 at 21:38

PowerShell, 22


Or, if the returned value has to typed as numeric, 23:

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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