1
$\begingroup$

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;
}
$\endgroup$
4
  • $\begingroup$ This is not the code for the heaviside but the sign function $\endgroup$ Jan 17 '20 at 11:42
  • $\begingroup$ 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. $\endgroup$ Jan 17 '20 at 11:43
  • $\begingroup$ true. So it's only to consider the case where $x=0$ ? However for numerical computations, we cannot handle such case ? $\endgroup$
    – Smilia
    Jan 17 '20 at 12:02
  • $\begingroup$ Why can't we? Multiplication by 0 for example yields an exact 0 result. $\endgroup$ Jan 17 '20 at 12:06
2
$\begingroup$

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
$\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.