4
$\begingroup$

The Sign function works in a very straightforward manner:

Sign[8]
Sign[-8]
Sign[0]
1
-1
0

Unfortunately, in my code I need Sign[0] to equal 1 or negative 1. I tried this but get a funny error:

ssign[x_] := Sign[2*(Boole[NonNegative[x]] - 0.5)]
Plot[ssign[x], {x, -5, 5}]

Plot::exclul: {NonNegative[x] - 0, (-0.5 + Re[Boole[NonNegative[x]]]) - 0} must be a list of equalities or real-valued functions. >>

Then, I tried a bunch of things, and this seemed like the best:

ssign[x_] := 2 UnitStep[x] - 1
Plot[ssign[x], {x, -5, 5}]

I am not too happy with this solution; there is still a zero coming out, just not at ssign[0]. Any ideas how to improve it?

$\endgroup$
  • 4
    $\begingroup$ At which x is 2 UnitStep[x] - 1 zero? I don't think there is one. It seems the best solution for your problem. $\endgroup$ – Michael E2 Feb 22 '16 at 1:23
7
$\begingroup$

The simplest way I can think of to define your ssign function is:

ssign[0 | 0.]= 1;
ssign[x_] := Sign[x]

Plot[ssign[x], {x, -5, 5}]

plot

$\endgroup$
4
$\begingroup$

Define your own:

mysign[x_] := Piecewise[{{1, x >= 0}, {-1, True}}]

mysign[-2]  (* Out: -1 *)
mysign[2]   (* Out:  1 *)
mysign[0]   (* Out:  1 *)
$\endgroup$
3
$\begingroup$

I agree that the UnitStep function defined by the OP is a perfectly good solution to this problem, but I thought I'd point out another option,

Unprotect[Sign];
Sign[0] = 1;
Protect[Sign];
Sign /@ {-2, -1, 0, 1, 2}
(* {-1, -1, 1, 1, 1} *)

Of course you have to be careful when modifying the definition of low-level built in functions, but, just as important, sometimes you have to live a little and take a few risks.

$\endgroup$
2
$\begingroup$

You can define your own sign. If you want Sign[0] to be randomly 1 or -1,

sign[x_] := If[Sign[x] == 0, RandomChoice[{-1, 1}], Sign[x]]
{sign[8], sign[-8], sign[0], sign[0], sign[0]}
{1, -1, 1, -1, -1}

though you could just choose one of the two.

$\endgroup$
2
$\begingroup$
sign[n_] := 2 Boole[10^10 n > RandomChoice[{1, -1}]] - 1

or using the same idea,

sign[n_] := Sign[10^10 n + RandomChoice[{1, -1}]]

sign[0] (*1*)
sign[0] (*-1*)
sign[-2] (*-1*)

unless $\left|n\right|<10^{^-10}$.


EDIT

I thought that you wanted the function to randomly choose -1 or 1 for 0. If one of these is fine, this is an even simpler way:

sign[n_] := 2 Boole[n >= 0] - 1
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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