# Find the absolute value of a number without built-in functions [closed]

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

• @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? – musefan Dec 9 '13 at 14:08
• @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
• 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

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

• If you write it as (%*) you also get complex magnitude for no extra characters. – FireFly Dec 7 '13 at 11:15
• 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  • 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 ## Perl: 5 characters s/-//  The example: perl -e '$_=-82.923; s/-//; print' # will print 82.923 or return it unless use 'print'

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

• 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


# Brainfuck, 40 chars

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


Or 35 chars if wrapping is allowed.

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


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

• 5 chars: √#^2& – chyanog 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
• 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

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

• ×× 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))

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

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

sqrt.flip(^)2$ # J, 13 Without using build-in functions (like signum and the like): f =: -]@.(0&<) f -1.253 1.253 f 0.91235 0.91235  # Python 2.7 (16 charcters) This one is the shortest here in python. (input()**2)**.5  Let n = input(), then • +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 EXCEL, 10: =SQRT(n^2)  -- n is a defined cell name with the input value. • Is using SQRT() really ok with the rules? – user19214 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... :-\ – user19214 Dec 1 '15 at 17:49 • VBA version of this, 12 bytes ?([A1]^2)^.5 – Taylor Scott Mar 25 '17 at 20:00 # 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  • 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 - 3128262423 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. # 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;  • 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 # 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... • You don't need a=. – Mama Fun Roll Nov 29 '15 at 17:18 ## Seriously, 874 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|. • 1½ is shorter than 21/. – user45941 Nov 28 '15 at 20:13 • Also try it online. – user45941 Nov 28 '15 at 20:14 • 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;}  • 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 # Befunge 98 - 117 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 &:02*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: &&\:02*1-*.".",.@  It is 17 chars in Befunge 98: &&\:02*1-*.'.,.@  Note: these print a space before the decimal point • 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 # 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)- +)%)  • 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: 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 # C# 6.0, 29 bytes double m(double n)=>n<0?-n:n;  • Note that this uses a feature of C# 6 (designed some time after the challenge was posted). – VisualMelon Nov 29 '15 at 15:24 • @VisualMelon Included C# 6.0 note there. – Yytsi Nov 29 '15 at 15:27 # 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. ## 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. • 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 # 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  # 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>  # PHP, 30 <?=($n=$argv[1])*(1-($n<0)*2);


# Gema, 2 characters

-=

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