Finding Square Root Using the Newton Rhapson Method

Page 1 of 1

1 Replies - 952 Views - Last Post: 10 November 2009 - 09:28 PM

#1 erik.price

• D.I.C Lover

Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

Finding Square Root Using the Newton Rhapson Method

Posted 06 November 2009 - 07:15 PM

Description: 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)Demonstrates the method for finding square root using the Newton Rhapson method, which is commonly used in calculators
```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
}
```

Is This A Good Question/Topic? 0

Replies To: Finding Square Root Using the Newton Rhapson Method

#2 pbl

• There is nothing you can't do with a JTable

Reputation: 8380
• Posts: 31,956
• Joined: 06-March 08

Re: Finding Square Root Using the Newton Rhapson Method

Posted 10 November 2009 - 09:28 PM

Good show... now we can redirect all those f* questions here