Find the absolute value of a number without built-in functions

4

1

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

Posted 2013-12-06T23:08:49.493

Reputation: 12 038

Question was closed 2015-12-14T12:16:10.227

What if absolute is a single-characters math operator in my language? – Adám – 2015-12-02T11:02:31.510

Sorry @NBZ but it's not one of the acceptable functions/operators in the last lines. – Timtech – 2015-12-04T12:04:02.750

4Apart 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 – 2015-12-14T11:34:57.833

Does putting the value on the stack count as returning it? – cat – 2015-12-14T11:53:26.470

Is the program allowed to loop forever and continue receiving input, finding the absolute value, and outputting it? – Justin – 2013-12-07T00:59:24.340

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 – 2013-12-07T05:47:46.437

My answers can handle all these values @Quincunx – Timtech – 2013-12-07T11:11:54.600

And yes, it is allowed to loop if you want. – Timtech – 2013-12-07T11:18:16.080

Umm, with those limited input values, only arbitrary precision/length integers work. Any regular floating point, etc won't work (can't store values that high). And are you talking about the infinitely many reals between those two? Also, your answer can really handle -10^-googol (ie -10^(-10^1000), something like -0.(1000 zeros)1). If it can, can it handle -10^(-googol^(googol^(googol^googol)))? That is a real number too. And -π is not exactly representable by decimal numbers (irrational), so almost every solution here fails. – Justin – 2013-12-07T19:19:40.100

@Quincunx As I said, all answers have a limit of -9E99 and 9E99. Also, pi is a real number so it must be handled. – Timtech – 2013-12-07T21:45:25.477

let us continue this discussion in chat

– Justin – 2013-12-07T23:18:58.897

@Quincunx Fine with me – Timtech – 2013-12-07T23:20:20.503

2@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 – 2013-12-09T14:08:24.483

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 – 2013-12-09T15:50:49.803

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 – 2013-12-09T17:57:52.620

@Doorknob I don't use that many C-related languages. – Timtech – 2013-12-09T21:16:48.290

1Well, irrelevant - operators in those languages are functions too. (Same in many many other langs.) So why don't those count? – Doorknob – 2013-12-09T21:41:39.490

@Doorknob If math operators aren't allowed either, how would you even write valid code to do this? – Timtech – 2013-12-09T21:50:31.417

8-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 – 2013-12-11T20:15:54.937

1You say single character math operations are allowed. This means that something like python's ** should be allowed because it is exactly equivalent to ^ (raise to the power). Either this or other answers with powers should be disqualified. – Justin – 2013-12-14T03:22:43.693

Answers

21

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

Gareth

Posted 2013-12-06T23:08:49.493

Reputation: 11 678

2Wouldn't this be considered a built-in sgn function? – LegionMammal978 – 2015-12-04T12:13:58.097

3If you write it as (%*) you also get complex magnitude for no extra characters. – FireFly – 2013-12-07T11:15:34.567

15

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

Doorknob

Posted 2013-12-06T23:08:49.493

Reputation: 68 138

Try writing a version that does support floating point (like my Befunge version now does) – Justin – 2013-12-07T00:56:46.987

1@Quincunx Challenge accepted ;) after I get back to a computer; commenting from a phone right now – Doorknob – 2013-12-07T01:24:46.070

@Quincunx Done, 4 characters :) – Doorknob – 2013-12-07T01:50:56.317

It looks like you just remove all instances of the minus sign (what I would do if I knew a fast way of doing so). What does / do? – Justin – 2013-12-07T06:10:59.497

I don't know any GolfScript, but it looks like / is the "remove" character. – Joe Z. – 2013-12-07T10:13:32.380

@Quincunx, it splits the string, so if the input is '-3' it will create an array ['' '3']. The remove character, which would be a more sensible way to do this, is -. But this is in any case arguably cheating. – Peter Taylor – 2013-12-07T11:30:26.683

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 – 2013-12-07T14:54:00.913

I said arguably cheating: the spec is vague on whether inputting and outputting a string is acceptable. – Peter Taylor – 2013-12-07T20:32:20.937

@PeterTaylor Nevertheless, that's the way GolfScript takes input, and the output is the same so that doesn't matter at all. – Doorknob – 2013-12-07T20:33:12.857

Doesn't this break the rule of "You may not use any built-in functions"? (as defined here as built-in)

– musefan – 2013-12-09T10:22:43.437

@musefan Well, by that logic, the C answer breaks the rules because it uses operator< and operator-, the J answer breaks the rules because it uses *, the Perl answer uses s, the Mathematica uses Sqrt and ², etc. – Doorknob – 2013-12-09T13:08:13.660

@Doorknob: yeah, but I can't be bothered to comment on all the answers. Yours has the most votes so I choose this one – musefan – 2013-12-09T14:03:19.527

@musefan Well, still, using your logic, all of these answers are completely disqualified. Maybe the OP needs to make the question more clear... – Doorknob – 2013-12-09T14:04:27.470

@Doorknob: Actually, I don't see the problem with the C one. I think operators are fine. I think it means built-in functions that perform more process intensive action, such as splitting an array... of course, that just my understanding. Like you say, the OP should be more specific – musefan – 2013-12-09T14:06:40.897

@Doorknob: See recent comments on the question. They explain that your answer violates the rule and is why it has not been accepted. This could also be true for the other answers – musefan – 2013-12-09T16:23:13.933

1@musefan Shall we start discussing that / is not a function but an operator??? – Howard – 2013-12-09T17:04:15.760

@Howard: No thanks, you call it what you want. I am not making the rules on whats accepted so it doesn't matter what I think – musefan – 2013-12-10T09:14:04.183

I'm late to the party, but the question specifies a clear and restrictive list of the operators that are allowed. In the list is the math operator /. The string operator /, no so much... – nitro2k01 – 2014-01-07T20:50:18.113

6

Perl: 5 characters

s/-//

The example:

perl -e '$_=-82.923; s/-//; print' # will print 82.923 or return it unless use 'print'

edem

Posted 2013-12-06T23:08:49.493

Reputation: 161

This is a good sed answer, too. – Toby Speight – 2015-12-01T17:40:49.007

5

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.

Joe Z.

Posted 2013-12-06T23:08:49.493

Reputation: 30 589

9It needs parentheses around the -a, otherwise it expands to --a. – Paul R – 2013-12-08T11:06:25.270

5

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

jpjacobs

Posted 2013-12-06T23:08:49.493

Reputation: 3 440

4

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

DavidC

Posted 2013-12-06T23:08:49.493

Reputation: 24 524

15 chars: √#^2& – chyanog – 2013-12-07T14:57:08.647

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 – 2013-12-07T16:44:14.363

2What about ? – FireFly – 2013-12-07T19:05:05.420

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 – 2013-12-07T21:04:22.653

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 – 2013-12-07T21:29:44.250

@FireFly Sqrt@#² yields a real number; Sqrt@#^2 yields a complex number. – DavidC – 2013-12-07T23:41:34.080

4

Brainfuck, 40 chars

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

Or 35 chars if wrapping is allowed.

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

alephalpha

Posted 2013-12-06T23:08:49.493

Reputation: 23 988

4

Python CLI, 20

lambda x:[x,-x][x<0]

boothby

Posted 2013-12-06T23:08:49.493

Reputation: 9 038

"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 – 2013-12-07T19:23:41.863

Yes, this doesn't count. It has to take input and return or output. – Timtech – 2013-12-07T21:46:31.403

@Quincunx fixed – boothby – 2013-12-08T14:50:38.333

Needs minor adjustment. (lambda x:[x,-x][x>0])(42) returns -42. – manatwork – 2013-12-08T14:57:03.693

must by lambda x:[x,-x][x<0] – AMK – 2013-12-08T18:40:28.807

2This isn't reusable though, should you include something like g= before it? Or is this really ok? – Justin – 2013-12-09T00:24:49.087

@Quincunx No. At the commandline, you can call _(x) immediately after executing the above to compute the absolute value of x. Or if you want to use the function more than once, you can say g=_. – boothby – 2014-01-06T23:10:07.323

4

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.

TwiNight

Posted 2013-12-06T23:08:49.493

Reputation: 4 187

×× should be enough, as per this J answer. – Adám – 2015-12-06T18:39:13.303

4

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

MartinM

Posted 2013-12-06T23:08:49.493

Reputation: 41

Yes, abs is not permitted – Timtech – 2013-12-08T22:48:53.630

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 – 2013-12-08T23:37:48.193

It's just that so many people are... but have an upvote :) – Timtech – 2013-12-09T11:48:39.553

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 – 2013-12-09T17:56:29.893

@Quincunx Splitting a string is a function – Timtech – 2013-12-10T22:27:07.093

3

Haskell, 14 characters

sqrt.flip(^)2$

Thom Wiggers

Posted 2013-12-06T23:08:49.493

Reputation: 191

3

J, 13

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

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

f -1.253
1.253
f 0.91235
0.91235

Eelvex

Posted 2013-12-06T23:08:49.493

Reputation: 5 204

3

Python 2.7 (16 charcters)

This one is the shortest here in python.

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

Let n = input(), then equation

Kartik

Posted 2013-12-06T23:08:49.493

Reputation: 149

+1, definitely a great answer. Wouldn't **.5 work though? – Timtech – 2013-12-26T23:45:54.540

@Timtech Yes, I didn't think of that. Thanks. BTW This is my first answer here. – Kartik – 2013-12-27T04:06:33.117

3

EXCEL, 10:

=SQRT(n^2)

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

user14011

Posted 2013-12-06T23:08:49.493

Reputation: 161

Is using SQRT() really ok with the rules? – None – 2015-11-28T21:18:25.450

@yeti - it's listed in the question... – Toby Speight – 2015-12-01T17:45:25.323

Ok... maybe I just was too tired to get my eyes open wide enough... :-\ – None – 2015-12-01T17:49:05.943

VBA version of this, 12 bytes ?([A1]^2)^.5 – Taylor Scott – 2017-03-25T20:00:14.027

3

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

Timtech

Posted 2013-12-06T23:08:49.493

Reputation: 12 038

Maybe edit this into your other answer instead? (I'll undownvote it if you do) – lirtosiast – 2015-11-29T20:31:28.510

@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 – 2015-12-01T23:15:46.460

There's also Anscos(angle(Ans at 5 bytes, which is interesting. – lirtosiast – 2015-12-01T23:36:27.720

Thanks for that suggestion - it's smart since cos(x) = cos(-x) – Timtech – 2015-12-02T00:26:18.880

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 – 2015-12-02T01:18:05.877

Interesting, nice alternative :) – Timtech – 2015-12-04T12:05:39.180

2

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.

Justin

Posted 2013-12-06T23:08:49.493

Reputation: 19 757

2

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

WallyWest

Posted 2013-12-06T23:08:49.493

Reputation: 6 949

2You don't need a=. – Mama Fun Roll – 2015-11-29T17:18:29.607

2

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

moala

Posted 2013-12-06T23:08:49.493

Reputation: 221

@urogen — unverified: *(long*)&f&=LONG_MAX; where f is a double. – moala – 2015-12-02T12:49:29.553

Nice one - clears the sign bit. But the question requires numbers between -9E99 and 9E99 - you need double. – ugoren – 2014-02-24T10:02:59.570

2

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

TanMath

Posted 2013-12-06T23:08:49.493

Reputation: 1 431

1 is shorter than 21/. – Mego – 2015-11-28T20:13:28.623

1

Also try it online.

– Mego – 2015-11-28T20:14:24.387

1Put 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 – 2015-12-25T17:25:39.293

1

Java - 36

This is the obvious solution.

double a(double b){return b<0?-b:b;}

Justin

Posted 2013-12-06T23:08:49.493

Reputation: 19 757

Is the semicolon required? I do more JavaScript than Java. – Timtech – 2013-12-06T23:48:42.957

@Timtech Yes. Every Java statement, apart from code blocks, needs a semicolon – Justin – 2013-12-06T23:55:04.560

1

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

Doorknob

Posted 2013-12-06T23:08:49.493

Reputation: 68 138

1

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

Justin

Posted 2013-12-06T23:08:49.493

Reputation: 19 757

I'm sorry, but the program has to be able to accept any real number as input. – Timtech – 2013-12-06T23:37:39.660

@Timtech Well, if the programming language is not capable of that, then... – Doorknob – 2013-12-06T23:38:47.047

@Doorknob It happens. Learning multiple programming languages may be the way to go. – Timtech – 2013-12-06T23:45:51.383

@Timtech notice that I have three answers in different languages... – Justin – 2013-12-06T23:46:26.840

I know, I was talking to Doorknob. – Timtech – 2013-12-06T23:47:40.140

@Timtech I have answers in 2 PLs as well :P – Doorknob – 2013-12-06T23:56:13.900

@Doorknob I see. I will add some more :) – Timtech – 2013-12-07T00:09:15.450

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 – 2013-12-07T11:47:06.923

@FireFly Is the . after the ~ supposed to be a :? It appears to work correctly when it is. Also, I think I need a ! in the infinite looping version (see edit) – Justin – 2013-12-07T17:15:49.810

Oh, yeah, you're completely right about :. Yup, looks good now. – FireFly – 2013-12-07T18:59:46.353

1

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

Shlomi

Posted 2013-12-06T23:08:49.493

Reputation: 121

I'm sorry, max is not allowed. No hard feelings, I am not supportive of all the answers that break the rules. – Timtech – 2013-12-15T23:56:40.103

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 – 2013-12-16T00:35:32.870

1

@Timtech Here is another definition: http://www.physicsforums.com/showthread.php?t=337952

– Justin – 2013-12-16T00:41:08.353

@Quincunx I understand that it can be defined mathematically, and I am fine with that. – Timtech – 2013-12-16T11:38:38.210

1

C# 6.0, 29 bytes

double m(double n)=>n<0?-n:n;

Yytsi

Posted 2013-12-06T23:08:49.493

Reputation: 3 582

Note that this uses a feature of C# 6 (designed some time after the challenge was posted). – VisualMelon – 2015-11-29T15:24:49.447

@VisualMelon Included C# 6.0 note there. – Yytsi – 2015-11-29T15:27:16.103

1

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.

Tom Carpenter

Posted 2013-12-06T23:08:49.493

Reputation: 3 990

1

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.

mroman

Posted 2013-12-06T23:08:49.493

Reputation: 1 382

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 – 2015-12-02T09:19:05.063

1

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.

a spaghetto

Posted 2013-12-06T23:08:49.493

Reputation: 10 647

1

Swift, 35 bytes (Not Competitive)

This is just for fun, and because Swift was developed after this question was posted, is not a competitive answer.

func a(v:Int)->Int{return v<0?-v:v}

un-golfed version

func absolute(value: Int) -> Int{
   return value < 0 ? -value : value
}

Jojodmo

Posted 2013-12-06T23:08:49.493

Reputation: 1 569

It is important to note that the language was invented after the challenge and therefore it technically is not a competitive answer. – TanMath – 2015-12-02T05:55:51.003

1

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

Emigna

Posted 2013-12-06T23:08:49.493

Reputation: 50 798

1

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>

Zach Gates

Posted 2013-12-06T23:08:49.493

Reputation: 6 152

1

PHP, 30

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

S22h

Posted 2013-12-06T23:08:49.493

Reputation: 151

1

Gema, 2 characters

Same as edem's Perl answer.

-=

Sample run:

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

manatwork

Posted 2013-12-06T23:08:49.493

Reputation: 17 865

0

PowerShell: 38

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

if(($x=+(read-host))-lt0){-$x}else{$x}

Iszi

Posted 2013-12-06T23:08:49.493

Reputation: 2 369

0

R 17 characters

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

Or 13 characters by adapting David Carraher Mathematica answer:

sqrt(scan()^2)

plannapus

Posted 2013-12-06T23:08:49.493

Reputation: 8 610

Max isn't allowed; I'd recommend switching to your 13 character solution. – Timtech – 2013-12-24T14:45:40.473

0

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.

Timtech

Posted 2013-12-06T23:08:49.493

Reputation: 12 038

1Square root is a function. – Gareth – 2013-12-11T20:19:53.470

1@Gareth It's dealing with mathematics. – Timtech – 2013-12-11T21:38:48.030

0

PowerShell, 22

(read-host)-replace'-'

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

+(read-host)-replace'-'

goric

Posted 2013-12-06T23:08:49.493

Reputation: 271

0

F#, 30

let a x=if x<0. then -x else x

goric

Posted 2013-12-06T23:08:49.493

Reputation: 271

0

Python (20)

lambda x:x*2*(x>0)-x

AMK

Posted 2013-12-06T23:08:49.493

Reputation: 506

0

Python - 27 chars

>>> f=lambda x:-x if x<0 else x
>>> f(-19.768)
19.768

KGo

Posted 2013-12-06T23:08:49.493

Reputation: 129

-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. – Justin – 2013-12-14T03:24:39.327

oh duhh... fixed it – KGo – 2013-12-14T03:35:15.240

0

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

Wasi

Posted 2013-12-06T23:08:49.493

Reputation: 1 682

0

No one use sed? similar as perl

s/-// 

BMW

Posted 2013-12-06T23:08:49.493

Reputation: 111

0

PHP, 40

<? $n=$argv[1];if($n<0) $n*=-1;echo $n;

Sammitch

Posted 2013-12-06T23:08:49.493

Reputation: 509

0

SQL - 43 chars

SELECT CASE WHEN @n<0 THEN -@n ELSE @n END;

ypercubeᵀᴹ

Posted 2013-12-06T23:08:49.493

Reputation: 101

Which SQL dialect? MSSQL lets you skip some spaces and the semicolon (40 chars): select case when @n<0then-@n else @n end, MySQL handles boolean (22 chars): select((@n>0)*2-1)*@n;. – manatwork – 2014-01-07T18:41:24.787

@manatwork, I was aiming for a DBMS agnostic answer. In MySQL, this would save 1 more char: SELECT(@n>0)*2*@n-@n; And the semicolon is not strictly needed in any dialect. – ypercubeᵀᴹ – 2014-01-07T21:36:47.070

0

Arcyóu, 16 bytes

(F(x)(^(^ x 2).5

This is an anonymous function taking one numeric type. It returns a floating point number equal to the number's absolute value. This is just nested exponentiation.

jqblz

Posted 2013-12-06T23:08:49.493

Reputation: 2 062

0

FP15 (7)

(*)sqrt

The (*) function squares a number. How does it work? In Haskell, (2*) means \x -> 2 * x and (*2) is \x -> x * 2, but (*) isn't \x -> x * x. In FP15, you can do (*) and even things like (*2+1) and (^2 - 5*sqrt). Also, in FP15, function composition is left-to-right.

Examples (~ is negation):

$ ./fp15-repl.py
> 12(*)sqrt
12.0
> 0(*)sqrt
0.0
> ~12(*)sqrt
12.0

If the signum function is allowed:

(*sgn)

If conditionals are allowed:

{(<0):~|_}

If max is allowed:

(~.max)
[,~]max

I created this language and it's still work in progress (no IO functions for now), but the last time I worked on it was early October.

Ming-Tang

Posted 2013-12-06T23:08:49.493

Reputation: 5 383

0

Go, 62 bytes

Pretty straightforward, I should think. Submitting a noncompilable standalone function feels so... wrong.

func a(){a:=""
Scanln(&a)
b,_:=Atoi(a)
if b<0{b=0-b}
Print(b)}

cat

Posted 2013-12-06T23:08:49.493

Reputation: 4 989

0

Note: this answer was written before the rule change mess, and was valid at time of posting.


Mouse-2002, 11 bytes

The DUP word is two bytes too long, and it requires a space after it. :( However, it still costs less than a var. (2 bytes per use)

?&DUP 0<[_]

Expanded:

?      ~ input
&DUP   ~ dup
0 <    ~ cmp
[      ~ if
  _    ~ signflip
]      ~ fi

Or, if leaving the value on the stack is not sufficient, then 12 bytes:

 ?&DUP 0<[_]!

This language needs implicit printing if nothing was.


$ mouse abs.mou
-100e99
100e99
$ mouse abs.mou
-INF
INF
$

Do I get a bonus if my program can compute every real number?

cat

Posted 2013-12-06T23:08:49.493

Reputation: 4 989

-1

LISP, 38

(define (abs x)
 (cond ((< x 0) (- x))
        (else x)
        ))

Ryaan Dias

Posted 2013-12-06T23:08:49.493

Reputation: 11

Please add also the character count. – ProgramFOX – 2013-12-27T09:14:28.307

-2

Ti-Basic 84, 10 bytes

Ans(2(Ans>0)-1

Timtech

Posted 2013-12-06T23:08:49.493

Reputation: 12 038

1This doesn't work. – lirtosiast – 2015-12-01T17:19:55.147

Fixed! Input & output on Ans which is the standard – Timtech – 2016-01-22T13:30:09.123

I won't remove my downvote, because this is essentially your third redundant TI-BASIC answer. – lirtosiast – 2016-01-22T16:40:21.803

Dude do you stalk my answers or something? – Timtech – 2016-01-22T23:06:23.260

1Do you not need to close the outer parenthesis? – Peter Taylor – 2013-12-06T23:26:29.537

1@PeterTaylor No, it is not required. – Timtech – 2013-12-06T23:30:20.050