I want to increase the exponent of a primitive double
d
, thus multiplying it by a power of two, for example 2^64.
I can do d *= math.pow(2, 64)
or calculate the power in advance if known: d *= 18446744073709551616
.
But I guess this is doing some expensive operations like multiplication, where we know in that case that all is needed is one addition of exponents. For example if it is possible to interpret the double as a long without converting it, we could do: (it does not work like that)
long longFromD = d; // imagine the casting does not change any bits from d.
double dTimes2ToThe64 = longFromD + (64L << 52) // shifting 64 to be aligned with the exponent of d
And that way we could get this multiplication with just an addition.
With the functions from the comment by @Johannes Kuhn:
public static double multiplyByAPowerOfTwo(double d, int exponent) {
long dInterpretedAsLong = Double.doubleToLongBits(d);
dInterpretedAsLong += ((long) exponent) << 52; // add exponents
return Double.longBitsToDouble(dInterpretedAsLong)
}
Another option per @phuclv's comment, using a HexadecimalFloatingPointLiteral
:
d *= 0x1.0p64;
For this method the exponent obviously has to be known in advance. This is presumably the same as d *= 18446744073709551616d;
, but it is quite a lot more elegant to write.
With this method we have one double multiplication which is hopefully about as efficient as just an addition of exponents (if a multiplication does happen, it's by one).