Reputation: 1021
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.
Upvotes: 1
Views: 7924
Reputation: 11
public class SquareRoot {
public void sqRoot_Efficient(int n){ //Time Complexity: O(log(n))
for(int i=1;i<=n;i++){
if((n/i)*(n/i) < n){
System.out.println(n/i);
break;
}
}
}
public static void main(String[] args) {
SquareRoot sr=new SquareRoot();
sr.sqRoot_Efficient(27);
}
}
Upvotes: 0
Reputation: 6802
I usually recommend Apache commons as a first place to look for most tasks.. But it appears the commons.math does not include sqrt().
Upvotes: -2
Reputation: 177604
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.
Upvotes: 1
Reputation: 1021
Math.sqrt
public static double sqrt(double a)
Returns the correctly rounded positive square root of a double value. Special cases:
Otherwise, the result is the double value closest to the true mathematical square root of the argument value.
Parameters:
Returns:
Upvotes: 1
Reputation: 21950
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?
Upvotes: 12
Reputation: 81936
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.
Upvotes: 4
Reputation: 4096
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.
Upvotes: 2
Reputation: 54600
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.
Upvotes: 4
Reputation: 6667
Try 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 :) .
http://www.merriampark.com/bigsqrt.htm
Upvotes: 6