Comments 4
Is Double length standardised in Java? You mentioned that it's 8 bytes long, but I wanted to make sure. Thanks for the article, by the way!
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.
One does not simply calculate the absolute value