Pull to refresh

Comments 5

Yes, see JLS 4.2.3:

The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).

Very funny. So even in Java the best way to do an abs operation is to dig into raw stored bits and zero the sign bit of an IEEE double representation. Aka, you have just invented some assembler.

I'm not super familiar with Java, but in other languages I would add 0 to the input value, since -0 + 0 = +0.

public static double abs(double value) { return (value + 0) < 0 ? -value : value; }

As an aside, re-interpreting a double as its integer representation is not free on all platforms.

Reference JDK implementation suggests the following code:

 @IntrinsicCandidate
    public static double abs(double a) {
        return (a <= 0.0D) ? 0.0D - a : a;
    }

Sign up to leave a comment.

Articles

Change theme settings