Java Glossary : power

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : P words : power.

power
To raise a number to a power, you can use Math.pow(double x, double p). Math.pow is a very expensive operation. It has to calculate the natural logarithm of x using polynomial interpolation (lots of multiplies), then it multiplies by p, then it calculates e to that power, again using polynomial interpolation. It also has to ensure if both operands are precice integers represented an doubles and the result is an integer that can be precisely represented as a double, then the result must be bang on. Avoid Math.pow if you possibly can. If you look at the source code for Math.pow you may think I am all wet. Much of this complexity is hidden inside the floating point hardware. Like all floating point routines, Math.pow's results are approximate. If you want perfection, use long, BigInteger or BigDecimal. For squared and cubed you can use x*x or x*x*x. For 2**n you can use 1<<n. For other integral powers you can use Patricia Shanahan's method, which it turns out is almost identical to the method Knuth gives on page 462 of The Art of Computer Programming Volume 2 Seminumerical Algorithms. The method dates back to 200 BC in India.
book_coverThe Art of Computer Programming Volume 2 Seminumerical Algorithms, Third Edition.
0-201-48541-9
Donald Knuth
amazon.com Barnes and Noble
amazon.ca chapters
amazon.co.uk amazon.de


view

Here is a fast integer log2 approximation:

/**
 * fast integer log2 approximation.
 * @param n number to take log2 of, n >= 5.
 * @return 8 * (log2( n ) - 1 )
 */
public static int bitLog( int n )
   {
   if ( n <= 8 )
      {
      return 2 * n;
      }
   else
      {
      int b = 31;
      while ( b > 2 && n > 0 )
         {
         b--;
         n <<= 1;
         }
      n &= 0x70000000;
      n >>= 28;
      return n + 8 *( b - 1 );
      }
   } // end bitLog


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 3130.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/power.html J:\mindprod\jgloss\power.html