# Using adolc for the sign function in c++

Here is an implementation of the sign function in C++ using Adolc librairy for automatic differentiation.

template<class Tdouble> Tdouble sgn(const Tdouble  &x)
{
Tdouble s_plus, s_minus, half(.5);
// set s_plus to sign(x)/2,  except for case x == 0, s_plus = -.5
condassign(s_plus,  +x, -half, +half);
// set s_minus to -sign(x)/2, except for case x == 0,s_minus = -.5
condassign(s_minus, -x, -half, +half);
// set s to sign(x)
return 0.5*(1-(s_plus - s_minus));
}


My question is: why do we need to compute s_minus and s_plus ? what are the advantages ?

What if I use simply :

template<class Tdouble> Tdouble sgn(const Tdouble  &x)
{
Tdouble res;
condassign(res,x,1,-1);
return res;
}

• This is not the code for the heaviside but the sign function – infinitezero Jan 17 at 11:42
• Furthermore, the sign function has three return values: -1 for x < 0, 0 for x = 0 and 1 for x > 0, so your version doesn't consider the middle case. – infinitezero Jan 17 at 11:43
• true. So it's only to consider the case where $x=0$ ? However for numerical computations, we cannot handle such case ? – Smilia Jan 17 at 12:02
• Why can't we? Multiplication by 0 for example yields an exact 0 result. – infinitezero Jan 17 at 12:06

Are you sure it is supposed to be sign function ?

According to this https://projects.coin-or.org/ADOL-C/browser/stable/2.1/ADOL-C/doc/adolc-manual.pdf?format=raw in section 1.8, condassign(a,b,c,d) is equal to

a = (b > 0) ? c : d


So the function posted is actually giving Heaviside function and not the sign function. It implements this function $$f(x) = \begin{cases} 0 & x < 0 \\ 1/2 & x = 0 \\ 1 & x > 0 \end{cases}$$ If $$x > 0$$

s_plus = -1/2, s_minus = 1/2, result = 1


If $$x=0$$

s_plus = s_minus = 1/2, result = 1/2


If $$x < 0$$

s_plus = 1/2, s_minus = -1/2, result = 0