Search code examples
c++functionmathsign

Zero-crossing Sign function


I have written a Sign function and am wondering whether it is correct or not (Stupid question to ask, I know!) I'm just interested in knowing whether this is the best method to solve this particular task:

template<typename T>
T sign(T n)
{
  if(n < 0) return -1;
  if(n > 0) return 1;
  return 0;
}

Would this give accurate enough results for large datasets? Can anyone see a problem, that I haven't come across that may arise when putting this into a real-life context?

Thanks


Solution

  • I would change return 0; to return n;. If n is NaN, sign should return NaN, not 0.