Question: Is there a better way to express the sign of a variable that will eventually hold a numeric value?

December 18 2013 jerbertz 25

1

Is there a better way to express the sign of a variable that will eventually hold a numeric value?

Up to this point, I have been using x/abs(x) (i.e. x/abs(x)) to represent the numeric sign of a variable. I can later manipulate, substitute, and evaluate any expression involving x/abs(x) without difficulty. For example:
> eval(x/abs(x), [x = -1]);
 -1

The problem is that it's inconvenient when the numeric value is identically zero:
> eval(x/abs(x), [x = 0]);
 Error, numeric exception: division by zero

Using a floating point zero works fine, but is not always practical:
> eval(x/abs(x), [x = 0.]);
 Float(undefined)

Now, the obvious tool here, sign(x), evaluates without complaint:
> sign(0);
 1

The problem with sign is that I cannot incorporate it into an expression that can be freely used later. For, the following produces an unexpected result:
> eval(sign(x), x = -1);
 1

Constructing the expression using layers of quotes don't help:
> expr := 200*' 'sign(x)' ';
 200 'sign(x)'

Simple uses of eval work fine:
> expr;
 200 sign(x)

> eval(expr, [x = -1]);
 -200

However, substitution with that expression using subs or eval doesn't produce the expected result:
> eval(a*b, [a = expr]);
 200 sign(x) b
> eval(%, [x = -1]);
 200 b

This also doesn't produce the expected result:
> subs(a = expr, a*b);
 200 sign(x) b
> eval(%, [x = -1]);
 200 b

I realize that this question might collapse into "How do I prevent a function from evaluating prematurely? " but cannot find any search terms that yield useful results.

sign_of_a_thing.mw

Please Wait...