This is the Java signum(double) method I am trying to imitate:

public static double signum(double d) {
    return (d == 0.0 || Double.isNaN(d))?d:copySign(1.0, d);

This is my version

public static double signum(double x) {
    return x != 0 ? x / abs(x) : 0;

I was thinking my method was not very readable, but I don't consider the Java method very readable, either. Is my method's readability okay? Also, how efficient is it, when compared to Java's signum method?

  • 1
    \$\begingroup\$ What is abs(...)? Is it Math.abs? \$\endgroup\$ – rolfl Aug 7 '15 at 16:52
  • \$\begingroup\$ Note that your method does not handle Double.NaN so your code is not the same as the Java version. Additionally, your code is unclear about what abs is, and there does not appear to be any effort to actually test its performance relative to the Java native one.... why do you want to do it differently unless you know it will be faster? Is it faster? Is this a learning exercise? \$\endgroup\$ – rolfl Aug 7 '15 at 16:55
  • \$\begingroup\$ @rolfl It's my own absolute value function (it works :P) \$\endgroup\$ – MCMastery Aug 7 '15 at 17:54

Floating-point division is probably the slowest basic arithmetic operation. For this simple function, it's entirely avoidable. I would also worry about whether the result of the division is exactly ±1.0.

There are three-and-a-half special cases evident in the model that you are trying to imitate; you've correctly handled two of them.

  • signum(Double.NaN) should return Double.NaN. Your version returns Double.NaN, but it is not obvious by inspection that it would do so.
  • signum(+0.0) returns +0.0, as expected.
  • signum(-0.0) returns +0.0, instead of -0.0, which is the model behaviour.
  • signum(Double.POSITIVE_INFINITY) and signum(Double.NEGATIVE_INFINITY) should return ±1.0, but your function incorrectly returns Double.NaN.
| improve this answer | |

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.