daily pastebin goal
67%
SHARE
TWEET

pow approximation with exponentiation by squaring

a guest Dec 10th, 2011 750 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static double pow(final double a, final double b) {
  2.         // exponentiation by squaring
  3.         double r = 1.0;
  4.         int exp = (int) b;
  5.         double base = a;
  6.         while (exp != 0) {
  7.                 if ((exp & 1) != 0) {
  8.                         r *= base;
  9.                 }
  10.                 base *= base;
  11.                 exp >>= 1;
  12.         }
  13.        
  14.         // use the IEEE 754 trick for the fraction of the exponent
  15.         final double b_faction = b - (int)b;
  16.         final long tmp = Double.doubleToLongBits(a);
  17.         final long tmp2 = (long) (b_faction * (tmp - 4606921280493453312L)) + 4606921280493453312L;
  18.         return r * Double.longBitsToDouble(tmp2);
  19. }
  20.  
  21.  
RAW Paste Data
Top