2
$\begingroup$

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.

$\endgroup$
3
  • $\begingroup$ should an exact zero input yield 1? $\endgroup$
    – george2079
    Oct 21, 2016 at 1:17
  • $\begingroup$ It doesn't matter, I'm never rounding 0 $\endgroup$
    – Bennnn
    Oct 21, 2016 at 1:29
  • $\begingroup$ "It doesn't matter, I'm never rounding 0" — Well, then you just want the Sign of the numbers, no? I didn't suggest it because Sign[0] == 0 in Mathematica. $\endgroup$
    – Szabolcs
    Oct 21, 2016 at 23:16

4 Answers 4

9
$\begingroup$

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.

$\endgroup$
9
$\begingroup$

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}

$\endgroup$
3
  • $\begingroup$ (+1) But Sign is Listable... You can save a character! $\endgroup$
    – kale
    Oct 21, 2016 at 2:36
  • $\begingroup$ Sign[0] gives the wrong result, tho... $\endgroup$
    – Michael E2
    Oct 21, 2016 at 9:33
  • $\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$
    – Michael E2
    Oct 21, 2016 at 22:58
4
$\begingroup$

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.

$\endgroup$
3
$\begingroup$
x/Abs[x]

Conveniently doesn't work for $x=0$.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.