Given a number N, output the sign of N:
- If N is positive, output 1
- If N is negative, output -1
- If N is 0, output 0
N will be an integer within the representable range of integers in your chosen language.
Formats into this triangle:
$ \ : - | 0 U % < g / l 0 P <
Old broken version that I understand:
Try it online! Currently nonworking until Dennis pulls; found some interpreter bugs.
Formats into this triangle:
$ \ : - % 0 U . . g / l 0 P <
How it works: The code, without directionals, is read as
$reads an integer from standard input.
:duplicates the top stack value.
0to the stack.
i>0to the stack and discards both values used (thanks, Luis Mendo).
Ppops the top stack value into the register.
0pushes 0 to the stack.
i<0to the stack and discards the values used.
Upulls the register onto the stack.
-computes a postfix subtract.
%prints the top stack value as an integer.
Idea thanks to caird.
Note that the X can be anything (except a new line), as it gets written over during run-time. It's just easier for explanation
Similar to my other Befunge answer, but this time it mods the first character by the ASCII for
1 first, so that a positive first digit will turn into a no-op, leaving the 1 on the top of the stack:
~ Read the first *character* of input - either a digit or "-" "1"% Mod the character by the ASCII value of 1. After this step, the character is a '-' for negative numbers, '0' for 0, and small, unprintable characters for positive numbers 90p Puts the character in the space with the X. 1 Pushes a 1 X 3 different options based on the character that was put here: - Negative: Subtract the 1 from the implicit 0 to get -1 0 Zero: Push 0 Positive: A no-op, which leaves the 1 on top . Prints out the top of the stack @ Ends the program
Uses a function named
a in the
execute if score @p n matches 0 run say 0 execute if score @p n matches 1.. run say 1 execute if score @p n matches ..-1 run say -1
"Takes input" from a scoreboard objective named
n, create it with
/scoreboard objectives add n dummy and then set it using
/scoreboard players set @p n 8. Then call the function using
U is the input number, and
g is the sign function on numbers. Output is implicit.
Pyth's sign function.
Matlab as well has a builtin for it.
As with many others, a built-in:
Please, read the first sentence of this meta post before voting.
Try it online:
Boring built-in, calls the .NET function that does exactly what it says on the tin. Ho-hum.
Try it online!
For 26 bytes however, we get the classic greater-than less-than equation
This, at least, has a little bit of logic and thought put into it. Try it online!
Best yet, though is 44 bytes, where we roll our own solution.
Here we take input
$b, stringify it, take the
.IndexOf('-') on it, and use it in an
if clause. If the negative sign isn't found, this returns
-1, which is truthy in PowerShell, so we turn
$b into a Boolean with
!, invert the Boolean with another
!, cast it as an int with
+, leave it on the pipeline, and
exit. This turns a positive integer (which is truthy) into
1, while turning
0. Otherwise, the
0 (meaning it was the first character in the string), which is falsey, so we skip the
if and just place a
-1 on the pipeline. In either case, output via implicit
Write-Output happens at program completion. Try it online!
This is just the obvious
(N > 0) - (0 < N) calculation.
& Read N from stdin. : Make a duplicate copy. 0` Calculate N > 0. \ Swap the second copy to the top of the stack. 0\` Calculate 0 > N. - Subtract the two comparisons: (N > 0) - (0 < N) .@ Output the result and exit.
Unfortunately this only works if the result of a modulo operation takes the sign of the divisor, which is not that common in Befunge implementations (in particular the reference interpreter doesn't work this way).
1 Push 1 onto the stack for later use. ~ Read a character of input (this will be '-' or an ASCII digit). "/"- Subtract 47. % Take the modulo of the 1 we pushed earlier with this difference. .@ Output the result and exit.
3 bytes with built-in:
p) the sign (
*) of the input (
Automatically threads over lists.
6 bytes without built-ins:
p) the division (
%) of the input (
i, taken from south with
S) by the absolute value (
+) of the input.
Conveniently, division by 0 yields 0 in Jellyfish.
This version also threads over lists.
Try it online!
Clojure, 23 bytes
#(condp > % 0 -1 1 0 1)
condp macro expands to "if less than 0 return -1, if less than 1 return 0 else 1".
(macroexpand '(condp > % 0 -1 1 0 1)) (let* [pred__7749 > expr__7750 %] (if (pred__7749 0 expr__7750) -1 (if (pred__7749 1 expr__7750) 0 1)))
should work on most systems.
PHP_INT_MIN has only one bit set: the most significant one. If this is set in the input, it is negative.
!$n (cast to integer by the subtraction) evaluates to
0 for positive values and
lame solution, 30 bytes
works also on floats.
Just to be different, here's a solution that avoids all those ugly arithmetic functions:
def s(n): try:r=len([:n])*2-n/n except:r=0 return r
Slicing a non-empty sequence
n is positive and
 when negative or zero, so to distinguish these cases,
n/n throws a divide by zero error for
This utilizes Qbasic's SGN() function.
: gets the input in variable
Original version, before I learnt that QBasic has a SGN() function:
18 bytes. Explanation
: Get 'a' from the command line ~a=b If a == b (and b==0 by default) |?a Then print a \?a/abs(a) Else, print a / abs(a) --> -2/2 leaves the req. -1, 4/4 = 1
; = [@: ======================================================= )) < ======================================================" @ ((((++ ======= < ===========" @ -)+)+)+((([!))+(( =============#==== (< ====" @ +)-[!))) ======#== ) < ========" >([!) "==# )) < @ -(-)[!+ ===========" =======#: >(([!! "===## @ +((-))[!- =========#:
;[> == output zero [@ : * start ================================================================================================== memory: [limit|limit_copy|counter_add|counter_sub|arg] move pointer back to arg )) < =================================================================================="=== increase counter limit @ ((((++ ================= set counters < ============" increase counter_add by one @ -)+)+)+ ((([! ))+(( ==============#====== reset limit (< =======" @ +)- [! ))) =========#==== try subtraction ) < ===========" > ( [! ) "====#== @ -(-) [! try addition ========# )) < ===============" > (( [! ! "=====#==# @ +((-)) [! ===========# output one output minus one +: -: === ===
The program maintains 5 memory fields (right to left):
The algorithm keeps on searching for zero in both (+ and -) directions, starting at the input value. It does k negative and k+1 positive steps on each iteration, then increases k by 2. Once zero has been found, 1 or -1 is output, depending from which side it was reached.
Detection of zero as input is a special case, handled right at the beginning.
There are a few other Octave/MATLAB answers, but two of the others are simply using a built in, and the other is significantly longer.
The anonymous function:
Quite simple. If a>0, the answer will be (1-0)=1. If a<0, the answer will be (0-1)=-1. If a==0 the answer will be (0-0)=0.
You can try online here. Simply run the above code and then try with
I don't like that 10 bytes of this is eaten up testing for zero, will continue to mull over that. The second half,
dd*vr1-d*v-p uses the square root of the square to calculate the absolute value of both our value to test and that value less one. Subtracting the latter from the former yields 1 for a positive value, -1 for a negative.