I am looking for square root functions (to use in java) that can give square roots upto atleast to 5-6 decimal places accurately. If there is a way to control accuracy of java.lang.Math.sqrt(double) or any external math library, please mention it.
views:
1533answers:
8Try out the code at this link, which uses Newton's method to compute square roots for large numbers (and gets BigDecimal output) to see if it fits your needs. If not, you can modify it :) .
You can use this formula to get it to an arbitrary accuracy:
http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number
I doubt that it will be particularly fast though. You'd also need a way to store numbers with larger than type(double) accuracy.
You can always implement your own using Newton's Method. Then you can make it as accurate as you want (at the cost of CPU of course).
Numerical Recipes in C has code and in-depth discussion. However make sure you check the license before using their code in your product.
You could roll your own using BigDecimal and a method like Newton-Raphson. That would allow you to specify a precision.
Have a look at Numerical Recipes if you need any inspiration.
I usually recommend Apache commons as a first place to look for most tasks.. But it appears the commons.math does not include sqrt().
What problem are you trying to solve? I believe java.lang.Math's sqrt is supposed to be accurate to the full double width. Do you need more than this?
Math.sqrt
public static double sqrt(double a)
Returns the correctly rounded positive square root of a double value. Special cases:
- If the argument is NaN or less than zero, then the result is NaN.
- If the argument is positive infinity, then the result is positive infinity.
- If the argument is positive zero or negative zero, then the result is the same as the argument.
Otherwise, the result is the double value closest to the true mathematical square root of the argument value.
Parameters:
- a - a value.
Returns:
- the positive square root of a. If the argument is NaN or less than zero, the result is NaN.
This question has been answered thoroughly enough already, but here is an experimental way to verify that Math.sqrt
is accurate:
import static java.lang.Math.*;
public class Test {
public static void main(String[] args) {
double max = 0;
for (int i = 0; i < 100; i++) {
double r = random();
double err = abs(pow(sqrt(r), 2) - r) / ulp(r);
if (err > max) max = err;
}
System.out.println(max);
}
}
This prints out 1.0
, confirming what the documentation says — that the value returned from sqrt
will be within one unit of precision to the exact answer.