Results 1 to 4 of 4
- 02-22-2013, 04:03 AM #1
Member
- Join Date
- Feb 2013
- Posts
- 60
- Rep Power
- 0
Newton's Square Root Method, need somebody to help see the problem.
Here's my output.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)); } }
Where's the extra .5 in 2.5 coming from?Enter a value for (n)
4
Newton(4.0) = 2.5
Math.sqrt(4.0) = 2.0
Last edited by LetsG0Blue; 02-22-2013 at 04:14 AM.
- 02-22-2013, 04:25 AM #2
Senior Member
- Join Date
- Jan 2013
- Location
- United States
- Posts
- 684
- Rep Power
- 1
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.
JimThe Java™ Tutorial
YAT -- Yet Another Typo
- 02-22-2013, 04:31 AM #3
Member
- Join Date
- Feb 2013
- Posts
- 60
- 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
- 02-22-2013, 04:38 AM #4
Senior Member
- Join Date
- Jan 2013
- Location
- United States
- Posts
- 684
- Rep Power
- 1
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.
JimLast edited by jim829; 02-22-2013 at 04:47 AM.
The Java™ Tutorial
YAT -- Yet Another Typo
Similar Threads
-
Creating recursion method to use Newton's method for square roots
By bdl1127 in forum New To JavaReplies: 2Last Post: 03-23-2012, 04:53 AM -
How to work out square root of Total
By ls7897 in forum New To JavaReplies: 23Last Post: 03-09-2011, 05:18 AM -
Find the square root with a particular method
By roud9 in forum New To JavaReplies: 2Last Post: 09-27-2010, 11:39 PM -
Simple square root problem!
By nortski in forum New To JavaReplies: 7Last Post: 04-01-2009, 02:11 PM -
Creating a New Method for Square Root Loop
By SapphireSpark in forum New To JavaReplies: 14Last Post: 02-25-2009, 01:21 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks