What's Here?
- Members: 306,728
- Replies: 840,911
- Topics: 140,495
- Snippets: 4,465
- Tutorials: 1,165
- Total Online: 2,494
- Members: 128
- Guests: 2,366
|
Demonstrates the method for finding square root using the Newton Rhapson method, which is commonly used in calculators
|
Submitted By: erik.price
|
|
|
Rating:
|
|
Views: 196 |
Language: Java
|
|
Last Modified: November 6, 2009 |
|
Instructions: Similar to the bisection method in design, but this method will perform better in almost every case (excluding perfect numbers, it'll find the answer, but just in a few more iterations) |
Snippet
public static double newtonSqrt(double x, double epsilon)
{
int ctr = 0; //ctr makes sure that the function will terminate eventually
double guess = 10; //initial guess to check
double result = guess-((guess*guess-x)/(2*guess));
if(x < 0){
return Double. longBitsToDouble(0x7ff8000000000000L );
//this represents NaN (Not-a-Number) because negative
//square roots don't work so well
}
else if(x == 0){
return 0; //prevents it from returning an incorrect answer
}
while((Math. abs(result*result - x ) > epsilon ) && ctr < 1000)
{
guess = result;
result = guess - ((guess*guess-x)/(2*guess));
ctr++;
}
return result;
//note: you can remove the epsilon variable from the method and replace it with an unchanging hardcoded value for set precision
}
Copy & Paste
|
|
|
|