Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 865
Matt9Atkins Avatar asked Feb 27 '13 00:02

Matt9Atkins


People also ask

What can I use instead of Math POW?

You can use x*x instead of pow(x, 2). For square root, you should first take a look on sqrt implementation (approximation method). Maybe you can find a better one, for example the Newton's method (on equation sqrt(N)-x=0).

Is sqrt faster than POW?

With regard to C standard library sqrt and pow , the answer is no. First, if pow(x, . 5f) were faster than an implementation of sqrt(x) , the engineer assigned to maintain sqrt would replace the implementation with pow(x, . 5f) .


2 Answers

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.

like image 179
Oleksi Avatar answered Sep 17 '22 15:09

Oleksi


"The power of 2" is squaring. You'd be better off doing that by multiplying the number by itself.

The library version of sqrt is probably faster than anything you could dig up elsewhere. If you call a C routine, you'll just add overhead from the cross-language call. But do you need accurate square roots, or would a table lookup of approximations do? Do the values repeat a lot, i.e. do you often need to calculate the roots of the same numbers? If so, caching the square roots in a HashMap might be faster than computing them.

like image 35
Carl Smotricz Avatar answered Sep 16 '22 15:09

Carl Smotricz