What I want to do is be able to round all numbers below 0 to -1 and all other number to 1. So that no matter what the input is it becomes either 1 or -1.
4 Answers
Use
2 UnitStep[x] - 1
where x
can be a number or any array of numbers.
If you never need to handle 0
, use Sign
.
Because the OP wrote "I'm never rounding 0", this will work fine:
Sign @ {-2, 0, 5}
{-1, 0, 1}
Issue with Sign[0] = 0
:
sign[x_] := If[x == 0, 1, Sign[x]]
or
sign[x_] := Piecewise[{{Sign[x], x != 0}, {1, x == 0}}]
then
sign /@ {-2, 0, 5} (* not Listable though *)
{-1, 1, 1}
Usually not recommended:
Unprotect[Sign];
Sign[0] := 1
Protect[Sign];
Sign @ {-2, 0, 5}
{-1, 1, 1}
-
$\begingroup$ (+1) But Sign is
Listable
... You can save a character! $\endgroup$– kaleOct 21, 2016 at 2:36 -
-
$\begingroup$ Ah, I hate it when someone can't write what they mean. After all, "So that no matter what the input is it becomes either 1 or -1" is pretty darn clear. $\endgroup$ Oct 21, 2016 at 22:58
Like this?
MyRounding[x_] = If[x < 0, -1, 1];
Examples:
MyRounding[5]
MyRounding[-5]
give +1 and -1. Note that this rounds zero to 1.
Sign
of the numbers, no? I didn't suggest it becauseSign[0] == 0
in Mathematica. $\endgroup$