Take the 2-minute tour ×
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? –  Quincunx 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? –  Quincunx Dec 7 '13 at 5:47
1  
@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
2  
@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  
-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

34 Answers 34

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) –  Quincunx 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

J, 4 characters

(**)

or if a function is required (5 characters):

x=:**

Usage:

   (**)9.3
9.3
   (**)-9.3
9.3

or for the function:

   x 9.3
9.3
   x -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 brackets around them turns them into a hook which gets evaluated like this: y * (*y). This isn't necessary for the function.

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

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

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.

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. –  David Carraher Dec 7 '13 at 16:44
1  
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

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

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. –  Quincunx Dec 9 '13 at 17:56
    
@Quincunx Splitting a string is a function –  Timtech Dec 10 '13 at 22:27

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

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

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

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

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. –  Quincunx 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? –  Quincunx Dec 9 '13 at 0:24

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

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

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 at 10:02

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. –  Quincunx Dec 16 '13 at 0:35
1  
@Timtech Here is another definition: physicsforums.com/showthread.php?t=337952 –  Quincunx 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

EXCEL, 10:

=SQRT(n^2)

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

share|improve this answer

Ti-Basic 84, 26 characters

:Input A:Return A(2(A>0)-1
share|improve this answer
1  
Do you not need to close the outer parenthesis? –  Peter Taylor Dec 6 '13 at 23:26
1  
@PeterTaylor No, it is not required. –  Timtech Dec 6 '13 at 23:30

PowerShell: 38

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

if(($x=+(read-host))-lt0){-$x}else{$x}
share|improve this answer

R 17 characters

max(n<-scan(),-n)

Or 13 characters by adapting David Carraher Mathematica answer:

sqrt(scan()^2)
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:

Y=X(2(X>0)-1

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

Haskell, 14 characters

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

PowerShell, 22

(read-host)-replace'-'

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

+(read-host)-replace'-'
share|improve this answer

F#, 30

let a x=if x<0. then -x else x
share|improve this answer

Python (20)

lambda x:x*2*(x>0)-x
share|improve this answer

Python - 27 chars

>>> f=lambda x:-x if x<0 else x
>>> f(-19.768)
19.768
share|improve this answer
    
-1. This does not comply with the specs. It does not return the absolute value, it simply negates the input (try f(300)). Fix it and I'll revert the vote. –  Quincunx Dec 14 '13 at 3:24
    
oh duhh... fixed it –  Karan Goel Dec 14 '13 at 3:35

AWK, 15

1,$0*=$1<0?-1:1

Note that, the following code can handle all values except 0

AWK, 13

 $0*=$1<0?-1:1
share|improve this answer

Your Answer

 
discard

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.