# Newton's Square Root Method, need somebody to help see the problem.

• 02-22-2013, 05:03 AM
LetsG0Blue
Newton's Square Root Method, need somebody to help see the problem.
Code:

```import java.util.Scanner; public class SquareRoot {         public static void main(String[] args) {                 Scanner in = new Scanner(System.in);                 System.out.println("Enter a value for (n)");                 double n = in.nextDouble();                 double x = 1, y = 1;                 x = y;                         while(Math.abs(x - y) <= 0.00001)                         {                                 x=y;                                 x = ((n / x) + x) / 2.0;                         }                                                 System.out.println("Newton("+n+") = "+x);                         System.out.println("Math.sqrt("+n+") = "+Math.sqrt(n));         } }```
Here's my output.

Quote:

Enter a value for (n)
4
Newton(4.0) = 2.5
Math.sqrt(4.0) = 2.0

Where's the extra .5 in 2.5 coming from?
• 02-22-2013, 05:25 AM
jim829
Re: Newton's Square Root Method, need somebody to help see the problem.
Well, initially, x-y == 0 which is less than .00001 so the loop goes thru once.

Then x = 2.5 and since 2.5 -1 > .00001 the loop exits.

Jim
• 02-22-2013, 05:31 AM
LetsG0Blue
Re: Newton's Square Root Method, need somebody to help see the problem.
But if I put a > there it equals 1 for the output of Newton
• 02-22-2013, 05:38 AM
jim829
Re: Newton's Square Root Method, need somebody to help see the problem.
That is because you chose x and y to be the same values to start so the loop would never enter if x = y = 1. So you could either chose different values for x and y. Or just change to a do while loop to force at least one iteration of the loop.

And I believe you want to set y = x.

Jim