power : Java Glossary
home P words local find no local find frame, full screen Google search web for topic jump to footer translate with Babelfish by Roedy Green ©1996-2008 Canadian Mind Products
Go to : punctuation 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 (all)
power
To raise a number to a power, you can use Math. pow(double x, double p).

This also works for non integer p and negative p. So you can compute roots with it too, e.g. the twelfth root of 2 is Math. pow( 2, 1.0d/12.0d ).

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 precise 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_cover recommend book⇒The Art of Computer Programming Volume 2 Seminumerical Algorithms, Third Edition.
 hardcover
ISBN10:0-201-48541-9
ISBN13:978-0-201-48541-7
publisher:Addison-Wesley
published:1998-10-15
by:Donald Knuth
Canadian flag amazon.ca. amazon.com. American flag
Canadian flag chapters.indigo.ca . powells.com American flag
French flag amazon.fr. barnesandnoble.com American flag
German flag amazon.de. amazon.co.uk. UK flag
Here is a fast integer log2 approximation:

CMP_homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.16] Spread the Net
You are visitor number 22,005.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/Mindprod website mirror)
http://mindprod.com/jgloss/power.html J:\mindprod\jgloss\power.html