# Return 0 for negative numbers using a short list of functions [duplicate]

I'm using a CAD software that allows you to calculate a value using a small set of built in functions. I have the formula complete for the input (call it 'x') of this formula, I just need to return either 0 if 'x' is negative or 'x' if not.

Here's the list of formulas/functions available:

• ABS (absolute)
• ACOS (Arccosine)
• ASIN (Arcsine)
• ATAN (Arctan)
• COS (Cosine)
• COSH (Hyperbolic Cosine)
• INT (Truncate to Integer)
• LOG (Log base e)
• LOG10 (Log base 10)
• SIN (Sine)
• SINH (Hyperbolic Sine)
• SQR (Square root)
• TAN (Tangent)
• TANH (Hyperbolic Tangent)

Is there anyway to achieve this?

Thanks in advance for any help!

• What does your software do if you try to take the square root of a negative number? If it generates an error you can catch then you can construct your answer pretty easily. – Ethan Bolker Apr 24 '19 at 13:14
• @Arthur That's why I started my comment with a question. In any case the accepted answer to the duplicate question is the way to go. – Ethan Bolker Apr 24 '19 at 13:18
• @EthanBolker its not a coded thing, just a UI to create formula (I'll add a screenshot to my post) – Kyle Beckman Apr 24 '19 at 13:19
• @EthanBolker You're right. I didn't see "you can catch" in your comment. – Arthur Apr 24 '19 at 13:19
• @MartinR yeah, its a duplicate, sorry... its frustrating when you search but nothing comes up for what you're trying to find... ended up using (Abs(x) + x)/2. Thanks! – Kyle Beckman Apr 24 '19 at 13:21

I think what you are looking for is $$\frac{x+|x|}{2}$$ which, for positive values of $$x$$, is $$\frac{x+x}{2}=x,$$ and for negative values of $$x$$ is $$\frac{x-x}{2}=0$$

• Yep, this is what I needed, thanks! (I have to wait a few minutes before I can mark it as the answer, but I will once I can) – Kyle Beckman Apr 24 '19 at 13:23

The absolute value can be seen as a "decision function", as its behavior ($$+x$$ or $$-x$$) depends on the comparison $$x\ge0$$.

It can be used for a sign function,

$$\text{sgn}(x)=\frac{|x|}{x}$$ (provided $$x\ne0$$).

From this you deriv a "positive" function ($$1$$ for positive, $$0$$ otherwise),

$$\text{pos}(x)=\frac{\text{sgn}(x)+1}2.$$

Then

$$x\text{ pos}(x)=\frac{|x|+x}2$$ has the desired behavior (even for $$x=0$$).

If the range of $$x$$ is bounded ($$|x|), you can also exploit the floor function (INT), via

$$\text{pos}(x)=\left\lfloor\frac xX\right\rfloor+1.$$

In case these functions would be missing, the absolute value is also

$$\sqrt{x^2},$$ and the floor can even be emulated from $$\arctan(\tan(x))$$

but this is very inefficient and not completely accurate.

Hint:

Since $$|x|=\begin{cases}x\text{ if }x\ge 0\\-x\text{ if }x<0\end{cases}$$ Then $$x+|x|=\begin{cases}x+x\text{ if }x\ge 0\\x-x\text{ if }x<0\end{cases}$$