3

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

user1725145
  • 3,993
  • 2
  • 37
  • 58
Phorce
  • 2,632
  • 13
  • 43
  • 76
  • 1
    possible duplicate of [Is there a standard sign function (signum, sgn) in C/C++?](http://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c) – Fred Foo Nov 14 '12 at 15:04
  • 3
    Wouldn't it be better with a return type of `int`? Currently you are depending that `-1` and `1` are convertable to type `T`. – john Nov 14 '12 at 15:05
  • What do you mean by “accurate enough results”? It gives *exact* results (unless you are using a truly weird type which cannot exactly – but approximately – represent 0, 1 and -1). How more accurate do you want them? – Konrad Rudolph Nov 14 '12 at 15:06
  • @john Hey, thank you! So instead of using templates to decide the return type, just return an int? – Phorce Nov 14 '12 at 15:07
  • @KonradRudolph Well, it doesn't since it's a template, but implemented just for `int` and `double` variants. – Šimon Tóth Nov 14 '12 at 15:07
  • 1
    Looks fine to me. I prefer your version to the proposed duplicate - easy to understand and shouldn't be significantly slower. – D Stanley Nov 14 '12 at 15:07
  • @Let_Me_Be See my edited comment. – Konrad Rudolph Nov 14 '12 at 15:08
  • @KonradRudolph You mean like complex numbers? – Šimon Tóth Nov 14 '12 at 15:08
  • Why has this been closed / I received bad rep? It's a question->this is a forum for programming questions ... It's clear, and is not really a duplicate of the previous post – Phorce Nov 14 '12 at 15:11
  • @Let_Me_Be No. I mean there is *no* (realistic) type which is unable to represent the result accurately (note that `unsigned` doesn’t qualify even though it cannot represent -1 at all, precisely because it cannot represent it *at all* – and furthermore the result would still be correct). – Konrad Rudolph Nov 14 '12 at 15:13
  • @Phorce Code review is explicitly offtopic. There is a specialized stackexchange site for that. – Šimon Tóth Nov 14 '12 at 15:19

1 Answers1

4

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

Henrik
  • 23,186
  • 6
  • 42
  • 92