Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
4  
At which x is 2 UnitStep[x] - 1 zero? I don't think there is one. It seems the best solution for your problem. – Michael E2 Feb 22 at 1:23
up vote 6 down vote accepted

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

share|improve this answer

Define your own:

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

mysign[-2]  (* Out: -1 *)
mysign[2]   (* Out:  1 *)
mysign[0]   (* Out:  1 *)
share|improve this answer

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.

share|improve this answer

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.

share|improve this answer
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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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