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

1. Member Join Date
Feb 2013
Posts
68
Rep Power
0

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

Java 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.

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?
Last edited by LetsG0Blue; 02-22-2013 at 04:14 AM.  Reply With Quote

2. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## 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  Reply With Quote

3. Member Join Date
Feb 2013
Posts
68
Rep Power
0

## 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  Reply With Quote

4. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## 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
Last edited by jim829; 02-22-2013 at 04:47 AM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•