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.
![]() |
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 | |||||||||||||||||
| ||||||||||||||||||
![]() |
and suggestions to improve this page to Roedy Green : | ||
| Canadian Mind Products | |||
| mindprod.com IP:[65.110.21.43] | |||
| Your face IP:[38.103.63.16] | ![]() | ||
| 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 | ||