HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Signum function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
functionsignumstackoverflow

Problem

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?

Solution

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.

Context

StackExchange Code Review Q#99278, answer score: 7

Revisions (0)

No revisions yet.