Search code examples
javafloating-pointprecisionieee-754exponent

How do I quickly calculate a large positive, or negative, power of 2 in Java?


I want to calculate powers of two larger than 262, so I must store the result in a double and can't use the (1L << exp) trick. I also want to store fractions representing negative powers of two.


Solution

  • Java provides java.lang.Math.scalb(float f, int scaleFactor) for this. It multiplies f by 2scaleFactor.