Java - Faster alternative to Math.pow() and Math.sqrt()

Matt9Atkins picture Matt9Atkins · Feb 27, 2013 · Viewed 15.5k times · Source

My program uses Math.pow() to compute a relatively large double number to the power of 2. Later on I need to find the square root of a very large double number. The problem is, I have to do this over a 100,000 times and it is taking really long. Is there any alternative that can speed this process up? Thanks

Edit: By large numbers I mean between 1000 to 10000 (So probably not that large in computing terms). And in terms of it taking a long time, it takes about 30 secs to do the function 500 times

Answer

Oleksi picture Oleksi · Feb 27, 2013

You are unlikely to find a better(faster) implementation than the Java Math one. You might have more luck trying to change the way you do the calculations in your algorithm. For example, is there any way you can avoid finding the square root of a huge number?

If this doesn't work, you can try implementing it in a more appropriate language that's meant for fast mathematical computations (something like Matlab).

Otherwise, you can try to optimize this in other areas. Perhaps you can try to cache past results if they are useful later.