Advertisement
Guest User

pow approximation with exponentiation by squaring

a guest
Dec 10th, 2011
2,590
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.53 KB | None | 0 0
  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.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement