g | x | w | all
Bytes Lang Time Link
004APLNARS250117T085616ZRosario
nan250117T030214ZRARE Kpo
040YASEPL240208T001907Zmadeforl
005Desmoslang Assembly230530T053309ZDadsdy
001Thunno 2230502T125323ZThe Thon
001Gaia230418T141950ZFerro Lu
024Common Lisp230418T121854Zcoredump
018minigolf230415T031207Zuser1176
003PARI/GP230409T060346Zalephalp
031Python230406T115336ZThe Empt
014Ly230402T010359Zcnamejj
028MMIX machine language230401T225234ZNoLonger
028Common Lisp230325T210227ZAlephSqu
005K ngn/k230323T145557Zcoltim
019PowerShell230324T210447ZJames Fl
008Raku230320T230025ZSean
005Wolfram Language Mathematica230324T062350Zatt
045Lua230322T110737ZDeadcode
023Haskell230322T231601Zorthocre
027Binaryencoded Golfical230323T004903ZSuperJed
684PIC16F88x Machine Code230322T181811ZBbrk24
003J230320T015228ZConor O&
051Go230320T132344Zbigyihsu
002Burlesque230322T114044ZDeathInc
016AArch64 machine code230322T021139ZNate Eld
nanPiet + asciipiet230322T020708ZBubbler
015Desmos230321T014652ZAiden Ch
009Factor230321T223504Zchunes
007Golfscript230321T222314ZNGeorges
003Julia 1.0230320T224120ZAshlin H
011HP‑41C series230320T010033ZKai Burg
008simply230320T232159ZIsmael M
003Pyth230320T140120ZCursorCo
012Ruby230320T154614ZG B
004Pip230320T153528ZDLosc
007Arturo230320T152254Zchunes
022C gcc230320T130812ZPeter
002Brachylog230320T125702ZFatalize
002MathGolf230320T080037ZKevin Cr
022Python 3230320T084706ZJitse
00205AB1E230320T075407ZKevin Cr
009K ngn/k230320T074030Zovs
nan230320T072923ZThe Thon
003polyglot230320T072759ZDominic
002BQN230320T065808ZDominic
015R230320T065805Zpajonk
153Nibbles230320T063324ZDominic
012Excel230320T051312ZJos Wool
002Japt230320T012120Znoodle p
016Kotlin230320T014819ZSeggan
014Java JDK230320T004327ZUnmitiga
015ARBLE230320T004922ZATaco
012Charcoal230320T010831ZNeil
029Retina 0.8.2230320T010233ZNeil
055Pascal230320T003900ZKai Burg
003Python 2230320T003735ZJonathan
017JavaScript ES6230320T002237ZArnauld
002Vyxal230319T235839Zlyxal
002Jelly230320T001308ZJonathan

APL(NARS), 4 Chars

×⎕-⎕

The sign of a-b

awk

function ___(_, __) { return (-(_ != __))^(_ <= __) }

This function is as polymorphic as it can get, because it can directly be used to compare either numerics or arbitrary strings (even raw binary data), and fully POSIX-compliant awk code (and branch-free loop-free and dependency-free, to boot)

Exponentiation (of boolean base and boolean exponent) is used to triangulate between 3 discrete output values. I preferred this approach because the nested boolean compares are at least partially orthogonal to each other instead of the near perfect -1 correlation of the standard approach.

YASEPL, 40 bytes

=x=a'=b'!a}1,b,3}3,b}2,b,2`3!$|`2!-|`1>x

takes 2 inputs from STDIN.

Desmoslang Assembly, 5 Bytes

I-IOT

I belive you had said that any negative or positive number works.

Thunno 2, 1 byte

Attempt This Online!

Built-in. Inputs in reverse order, b then a. Requires \$\le 2.2.0\$, as this was changed in Thunno \$2.2.1\$.

Thunno 2, 2 bytes

Same as most other answers: sign of a-b. Inputs in normal order, a then b. Works in all versions.

Attempt This Online!

Gaia, 1 byte

C

Try it online!

Common Lisp, 24 bytes

(compose'floor'signum'-)

This is the functional composition of functions floor, signum and -.

The signum function computes the sign and return the expected values, but for floating point values the result is also a float, either -1.0, -0.0, +0.0 or +1.0. That's why the floor operation is used to convert the result back to an integer.

minigolf, 18 bytes

TiiT*+1+,:1+s,T+__

Attempt This Online! (Since minigolf is not properly added to ATO yet, I'm using a Python runner here.)

Explanation

We use -1 as the base of our output. If a-b >= 0, we increment -1 a-b+1 times. However, if our output reaches 2, we decrement it back to 1.

T                 0, Base our signum output on -1 _
iiT*+             0, a + b * -1 _
1+                0, increment the result _
,                 0, Repeat that many times: _
  :1+s            0, Increment signum but keep the original value _
                  0, This is useful because we only want to _
                  0, decrement once in the 2 case _
  ,               0, If our previous signum value is 1: do this once _
    T+            0, Add signum value by -1 _
  _               0, End foreach loop _
_                 0, End foreach loop _

0, Implicit output the signum value left on the stack _
```

PARI/GP, 3 bytes

cmp

Attempt This Online!

Python, 31 Bytes

lambda a,b:(x:=a-b)and x/abs(x)

-7 Bytes from The Thonnu.

abs(x) gets the absolute value of x (think of it as scissors that can cut the - sign off numbers).

Ly, 14 bytes

nns=!rlLfp2*,*

Try it online!

Longer than I'd hoped, but I couldn't find a shorter way to do it given the instructions available...

nns             - read in two numbers, stash the second one away
   =!           - are they equal? invert result so "0" is set for equal
     rl         - reverse stack, recover the second number
       L        - do "less than" comparison
        fp      - delete the first number (it's still on the stack)
          2*,   - converts "0" to "-1" and "1" stays "1"
             *  - multiple by "are they equal?" val to get "0" as needed

MMIX machine language, 2 instrs (8 bytes)

For s64:

00000000: 30000001 f8010000                    0¡¡¢ẏ¢¡¡

Disassembled:

    CMP $0,$0,$1        // x = x <=> y
    POP 1,0             // return x

For u64:

00000000: 32000001 f8010000                    2¡¡¢ẏ¢¡¡

Disassembled, the only change is the first instruction is now CMPU.

For f64:

00000000: 01000001 f8010000                    ¢¡¡¢ẏ¢¡¡

And this time the first instruction is FCMP.

All of these functions are excellent candidates for inlining.

Common Lisp, 28 bytes

(lambda(a b)(signum(- a b)))

K (ngn/k), 5 bytes

-/<?,

Try it online!

An alternative version that takes the input as a list of two numbers is -/<?:.

PowerShell, 19 bytes

[math]::Sign($a-$b)

Try it online!

Raku, 8 bytes

+(*cmp*)

Try it online!

cmp is Raku's built-in smart comparison operator, and *cmp* is an anonymous function that passes its arguments to that operator.

Unfortunately for this challenge, cmp doesn't return -1, 1, or 0, but one of the enumerated values Less, More, or Same, so the prefix + operator converts those values into their integer values.

The non-golfy solution would be to just compose the two operators:

&prefix:<+> o &[cmp]

Wolfram Language (Mathematica), 5 bytes

Order

Try it online!

Input Order[b, a]. Works on any atomic numbers.

Note the reversed order of inputs.

Lua, 45 bytes

load"a,b=...return a>b and 1or a<b and-1or 0"

Try it online!

Lua has a strict type system, and there is no shorter way than a and 1or 0 to convert a boolean to an integer.

This version works for all comparable types (e.g. integer, floating point, and string).

Lua, 35 bytes

load"a,b=...return-1+2/(0^(a-b)+1)"

Try it online!

This is based on my answer to Output the sign. It gives the correct result for all floating point inputs, and most integer inputs.

It doesn't meet the requirements of this challenge for integer inputs, as it will fail when passed, for example, math.maxinteger and math.mininteger (as demonstrated in the test harness), because subtracting one from the other results in an overflow. But it does fully work for all floating point inputs, thus meeting the challenge's requirements for that type.

Haskell, 24 23 bytes

a#b|a<b= -1|a>b=1|0<1=0

Try it online!

-1, thanks to Unrelated String!

The 'nicer' solution of ((pred.fromEnum).).compare is 26 bytes.

Binary-encoded Golfical, 27 bytes

Hexdump of binary encoding:

00 30 07 15 14 14 14 14 17 17 0c 01 14 14 14 17
00 01 02 01 1c 15 3b 4e 23 26 1d 

Original program image:

enter image description here

Magnified 40x with RGB colors labeled:

enter image description here

Based on my answer here.

PIC16F88x Machine Code, 6 words (84 bits)

A function that expects a to be at address 0x70 in memory, and b to be in register W. Returns the result in register W.

The PIC16 uses 14-bit instruction words. Because the number of words is even, this function can be represented exactly in hex with no padding:

0bc1d03d001ff0dfff401

In mpasm syntax, that is:

    SUBWF 0x70,F   ; Subtract W from the value at 0x70. Leave the result at
                   ; 0x70.
    BTFSC STATUS,2 ; Check the zero flag (bit 2 of the STATUS register) and skip
                   ; the next instruction if it's not set.
    RETLW 0x00     ; Set the W register to 0 and return.
    BTFSC 0x70,7   ; Skip the next instruction if the MSb of the value at 0x70
                   ; is 0 (i.e. the result of subtraction is positive).
    RETLW 0xFF     ; Set the W register to 0xff (-1) and return.
    RETLW 0x01     ; Set the W register to 1 and return.

Bit for bit, this is encoded as:

00 0010 1111 0000
00 0010           SUBWF
         111 0000       0x70
        1                    F

01 1101 0000 0011
01 11             BTFSC
         000 0011       STATUS
     01 0                      2

11 0100 0000 0000
11 01             RETLW
        0000 0000       0x00
     00                      (ignored)

01 1111 1111 0000
01 11             BTFSC
         111 0000       0x70
     11 1                    7

11 0111 1111 1111
11 01             RETLW
        1111 1111       0xff
     11                      (ignored)

11 0100 0000 0001
11 01             RETLW
        0000 0001       0x01
     00                      (ignored)

The PIC16F88x family of microcontrollers have four memory banks of 128 bytes each. (These are actually bytes this time, and not 14-bit words.) Which one is used depends on the value of the STATUS register. However, addresses 0x70 through 0x7f are the same on all banks, so by placing the operands there the function doesn't have to change banks to access them. I'm not aware of any standard calling convention as far as argument location goes, but the return value being in register W is standard (hence the existence of the RETLW instruction).

J, 3 bytes

*@-

Try it online! The 3-byte solution >-< featured in a few other answers also works for the same byte count (greater-than minus less-than).

Works for any numeric type. Anonymous dyad.

Explanation

*@-
*     sign
 @    of
  -   difference

Go, 52 51 bytes

func(a,b int)int{n:=1
for-1<n&&b-a<n{n--}
return-n}

Attempt This Online!

By @Kevin Cruijssen. Uses a for loop to get the return value rather than a chain of ifs.

Changelog

Old answer, 56 bytes

func(a,b int)int{n:=0
if a>b{n=1}
if a<b{n=-1}
return n}

Attempt This Online!

Go doesn't have any sort of built-in abs like C, or default type methods like Java, so a function it is. Go also doesn't have ternary expressions, so the old-school "set and check" pattern is needed.

Burlesque, 2 bytes

cm

Try it online!

Built in compare.

AArch64 machine code, 16 bytes

AArch64's conditional select instructions get their time to shine.

0000000000000000 <spaceship>:
   0:   eb01001f    cmp x0, x1
   4:   9a9f07e0    cset x0, ne
   8:   da80a400    cneg x0, x0, lt
   c:   d65f03c0    ret

cset sets the destination register to 1 or 0 according to whether the condition code is true or false. (Fun fact: it's actually an alias for csinc x0, xzr, xzr, eq, where csinc X, Y, Z, cond sets X to Y if the condition is true, and to Z+1 if false.)

cneg X, Y, cond sets X either to -Y or Y according to whether the condition is true or false. (Alias for csneg X, Y, Y, cond.)

Several other permutations are also possible, such as

cset x0, gt              // x0 = (a > b) ? 1 : 0
csinv x0, x0, xzr, lt    // x0 = (a < b) ? x0 : ~0

Piet + ascii-piet, 21 bytes (4×7=28 codels)

vekabrA krbtkFbks?Tbb

Try Piet online!

Just a minor variation from my answer to "output the sign". Takes two numbers and subtracts instead of taking just one number, and then the rest follows the same logic.

A1->A4
inN inN -    [a-b] Take two numbers and subtract
A4->A7->B7->B5
dup 1 ! > !  [a-b a-b<=0]
CC+          [a-b] Continue on row B if a-b<=0, shift to row C otherwise
B5->B2
! 1 -        [(a-b==0)-1] -1 if a-b!=0 (which implies a-b<0), 0 otherwise
C5->C2
1            [a-b 1] Ignore the previous number and push 1
C2->C1
outN         Print the top number and exit

Desmos, 15 bytes

f(a,b)=sgn(a-b)

Try It On Desmos!

Factor, 9 bytes

[ - sgn ]

Try it online!

Sign of difference. Factor has a <=> word, but it returns +lt+, +eq+, and +gt+ symbols.

Golfscript, 7 bytes

.~>\~<-

read from stdin

# explanation:
. # duplicate
~ # unpack
> # gt 
\ # store the result and get duplicated stdin again
~ # unpack
< # lt
- # gt-lt

Julia 1.0, 13 3 bytes

cmp

Try it online!

-10 bytes thanks to MarcMush: use cmp

Alternate solution, 13 bytes

a%b=sign(a-b)

Try it online!

Alternate solution (15 bytes)

a%b=(a>b)-(a<b)

Try it online!

Some operators have lower precedence than < and >. Redefining one of them as - removes the need for parentheses but doesn't save bytes overall:

~=-
a%b=a>b~a<b

Try it online!

HP‑41C series,  9  11 Bytes

a needs to be entered first, then b, so a is placed in the Y register and b in the X register.

01♦LBL⸆S     5 Bytes    global label requires 4 + m Bytes
02 SF 24     2 Bytes    ignore “out of range” errors, and instead
                        return ±9.999999999E99 as an approximation
03 −         1 Byte     X ≔ Y − X
04 X≠0?      1 Byte     if X = 0 then skip next line
05 SIGN      1 Byte     ↯ `SIGN` returns `1` for zero
06 RTN       1 Byte     `RTN` does not affect local label search

simply, 8 bytes

Does exactly the expected.

&compare

This is a built-in function that simply returns the expected result.


Example:

Code-like

// Should output 1
echo &compare(2, 1);

Plain-English-like

// Should output -1
Show the result of calling &compare with the arguments 1, 2.

Test code:

This shows test results in a nice pretty table.

// Test data - self-explanatory
// Example 5 shows an error, as an example
$tests = &json_decode(<<<JSON
[
    {"a": 0, "b": 1, "result": -1},
    {"a": 1, "b": 2, "result": -1},
    {"a": 2, "b": 1, "result": 1},
    {"a": 2, "b": 2, "result": 0},
    {"a": 3, "b": 2, "result": 0}
]
JSON);

// Make the table pretty
$settings = call !TABLE->getDefaultSettings();
$settings->classHeader = &str_concat($settings->classHeader, " table-dark");
$settings->classBodyCell = &str_concat(
    $settings->classBodyCell,
    " text-center"
);
$settings->classBodyFirstCol = &str_concat(
    $settings->classBodyFirstCol,
    " text-center table-dark"
);
$settings->classHeaderItems = &str_concat(
    $settings->classHeaderItems,
    " w-25"
);

// Create the table
$table = call !TABLE->create($settings);

call $table->setHeader(["", "A", "B", "Result"]);

each $test in $tests {
    // This is where the function runs
    $result = &compare($test['a'], $test['b']);
    
    call $table->addRow(
        &iff(
            $result == $test["result"],
            "✔️",
            &str_concat("❌ (", $test["result"], ")")
        ),
        $test['a'],
        $test['b'],
        $result
    );
}

call $table->show();

Result:

Result of running the example

This is an example of how the table will look like.

Pyth, 3 bytes

._-

Try it online!

Defines a function which takes two inputs b, a.

Explanation

  -    # subtract the second argument from the first
._     # take the sign

Ruby, 12 bytes

->a,b{a<=>b}

Try it online!

(feels like cheating)

Pip, 4 bytes

aCMb

There's a built-in operator for that. (Fun fact: in my original designs for Pip, this operator was <=>, until I realized that having a 3-character operator in a golfing language was silly.)

Attempt This Online!

Arturo, 7 bytes

compare

Try it

Builtin.

(In Arturo, <=> is the between operator. 5 <=> 1 10 would return true.)

Arturo, 33 bytes

$[a b][(a>b)?->1->(a=b)?->0->0-1]

Try it

Non-builtin.

Arturo doesn't have a sign function or integer booleans, so I couldn't think of anything better than a nested ternary.

C (gcc), 22 bytes

This is practically @TobySpeight's answer now since he changed the entire algorithm.

f(a,b){a=(a>b)-(a<b);}

Try it online!

Brachylog, 2 bytes

-ṡ

Try it online!

Same answer as many other esolangs.

Explanation

-     Subtract
 ṡ    Sign

MathGolf, 2 bytes

Try it online.

Explanation:

,  # Subtract the second (implicit) input by the first (implicit) input: b-a
 σ # Get the sign of that (-1 if <0; 0 if ==0; 1 if >0)
   # (after which the entire stack is output implicitly as result)

Python 3, 22 bytes

lambda a,b:(a>b)-(a<b)

Try it online!

Python 3 lacks the builtin cmp

-1 thanks to Dominic van Essen

05AB1E, 2 bytes

.S

Builtin. Takes the inputs in the order \$b,a\$.

Try it online.

Explanation:

.S  # Compare the second (implicit) input-integer `a` with the first (implicit)
    # input-integer `b`, and push -1 if a<b; 0 if a==b; or 1 if a>b
    # (which is output implicitly as result)

K (ngn/k), 9 bytes

1&-_1^-%-

Try it online!

K lacks a sign builtin, which makes this a bit trickier.

-%- negative square root of a-b. This is negative if a>b, zero if a=b and -0n (negative null value) if a<b.
1^ Replace null with 1.
-_ floor and negate the number. In combination with the earlier - this does a ceil on the square root.
1& take the minimum of 1 and this number.

If the input was restricted to integers, 0 1' would calculate the sign, leading to 0 1'- as a full solution.

Thunno, \$ 3\log_{256}(96)\approx\$ 2.47 bytes

_za

Attempt This Online!

Sign of a-b.

polyglot, 3 bytes

<=>

Try it in Perl!

<Insert other languages that already have the exact <=> operator here>

BQN, 2 bytes

×-

Try it at BQN REPL

×       # sign of
 -      # left arg minus right arg

BQN, 3 bytes

<->

Try it at BQN REPL

This clearly isn't the shortest possible solution in BQN (see above), but it is particularly visually appealing due to its similarity to the C++/Perl/etc <=> operator.

<->     # 3-element train abc 
        # ( x abc y expands to: (x a y) b (x c y) )
<       # left arg < right arg
 -      # minus
  >     # left arg > right arg 

(a similar 'reverse-comparison' operator - >-< is also possible and also [I think] looks nice)

R, 15 bytes

\(a,b)sign(a-b)

Attempt This Online!

Nibbles, 1.5 bytes (3 nibbles)

`$-
`$-         # full program
`$-$@       # with implicit args shown;
`$          # get sign of
   $        # arg1
  -         # minus
    @       # arg2

enter image description here

Excel, 12 bytes

=SIGN(A1-B1)

where A1 and B1 contain a and b respectively.

Japt, 2 bytes

gV

Try it

g   # sign of the difference of implicit first input and
 V  # second input

Kotlin, 16 bytes

Float::compareTo

Try it online!

Annoyingly, longer than Java.

Kotlin, 14 bytes

Int::compareTo

Try it online!

Works only on ints (I edited this after seeing that Java got edited).

Java (JDK), 14 bytes

Float::compare

Try it online!

Java (JDK), 13 bytes

Long::compare

Try it online!

Only supports integers.

ARBLE, 25 15 bytes

lt(a,b)-gt(a,b)

Same as Arnauld's JS solution. Unfortunately Verbose, throwing away the advantages of the langauge.

Try it online!

Charcoal, 12 bytes

NθNηI⁻›θη‹θη

Try it online! Link is to verbose version of code. Explanation: Port of @Arnauld's JavaScript answer.

Alternative approach, also 12 bytes:

≔⁻NNθI÷θ∨↔θ¹

Try it online! Link is to verbose version of code. Explanation: Divides the difference between the numbers by the absolute value of the difference, or 1 if that's zero.

Retina 0.8.2, 29 bytes

\d+
$*
(1*) \1
0
1+0
1
01+
-1

Try it online! Link includes test cases. Only works on non-negative integers. Explanation:

\d+
$*

Convert to unary.

(1*) \1
0

Try to subtract; this will leave 0 if a = b.

1+0
1

If a > b then replace the result with 1.

01+
-1

If a < b then replace the result with -1.

Pascal, 55 Bytes

function f(a,b:real):real;begin f:=ord(a>b)-ord(a<b)end

Python 2, 3 bytes

cmp

A built-in function that accepts \$a\$ and \$b\$ and returns \$a \lt = \gt b\$.

Try it online!

JavaScript (ES6), 17 bytes

Expects (a)(b).

a=>b=>(a>b)-(a<b)

Try it online!

Vyxal, 2 bytes

Try it Online!

Takes input as b then a. Simply subtract the two numbers and get the sign of the result.

Alternatively a more fun looking, symbol only answer comes in at 17 bytes:

Vyxal, 17 bytes

-:::-<[::-$~-|:]/

Try it Online!

Also takes b then a. This answer is purely just for fun, and could be made shorter by using numbers and letters (-D0<[N|:]/).

Explained

-:::-<[::-$~-|:]/
-:                # Subtract the two numbers and push a copy
  ::-             # Push 0 to the stack by subtracting the top of the stack from itself
     <            # Is the original top of the stack < 0?
      [           # If so:
       ::         #   Duplicate the top of the stack twice. This could just be `D`, but that wouldn't be a symbol.
         -        #   Subtract those copies to get 0 again.
          $~-     #   Push the 0 under the top of the stack, and subtract without popping. The stack is now [0, a - b, -(a - b)]
             |    # Otherwise:
              :   #   Just duplicate the top of the stack
               ]  # this whole if statement was to make sure there was [a - b, abs(a - b)] as the stack
                / # Divide the top two stack items to get either -1, 0 or 1. negative/positive = -1, 0/0 = 0 and positive/positive = 1

Jelly, 2 bytes

_Ṡ

A dyadic Link that accepts \$a\$ on the left and \$b\$ on the right and yields \$a \lt = \gt b\$.

Try it online!

How?

_Ṡ - Link: a, b
_  - (a) subtract (b)
 Ṡ - sign -> -1, 0, or 1