What's Here?
- Members: 306,728
- Replies: 840,911
- Topics: 140,495
- Snippets: 4,465
- Tutorials: 1,165
- Total Online: 2,518
- Members: 127
- Guests: 2,391
|
A method which will find the square root of a number, given the number to find the root of, as well as an adjustable precision
|
Submitted By: erik.price
|
|
|
Rating:
|
|
Views: 218 |
Language: Java
|
|
Last Modified: November 6, 2009 |
|
Instructions: Using bisection might not be the most efficient way of finding square roots, but when given a perfect square, it will find the answer in only 1 iteration |
Snippet
public static double biSqrt(double root, double prec) {
double low = 0;
double high = Math. max(root, 1. 0); //fixes a bug that would cause numbers less than 1 to fail
double guess = (low+high)/2.0;
int ctr = 0; //ctr is used to make sure that with some
//numbers which can't be represented exactly don't inifitely repeat
if(root < 0){
return Double. longBitsToDouble(0x7ff8000000000000L );
//this represents NaN (Not-a-Number) because negative
//square roots don't work so well
}
else if(root == 0) {
return 0; //prevents it from returning an incorrect result
}
while((Math. abs((guess*guess ) - root ) > prec ) && (ctr < 1000)) //checks to see if the result is "good enough"
{
if((guess*guess) < root)
low = guess;
else
high = guess;
guess = (low+high) / 2.0;
ctr++;
}
return guess;
//just a note: you can remove the prec variable from the method and replace it with an unchanging hardcoded value for set precision
}
Copy & Paste
|
|
|
|