Results 1 to 3 of 3
- 03-21-2012, 04:14 AM #1
Member
- Join Date
- Jan 2012
- Posts
- 26
- Rep Power
- 0
Creating recursion method to use Newton's method for square roots
Im really just not quite understanding recursion. I have created an iterative method to do this and it is working successfully. My iterative method is as follows:
public static double squareRootIter (double num, double guess) {
double x = guess;
double epsilon = 1E-9;
while(Math.abs(num - (x*x)) > epsilon) {
double b = x - (((x*x) - num)/ (2*x));
x = b;
}
return x;
}
I just need to turn this into a recursive method. I dont really even know where to start. Below is the method that must be used. Can someone please explain recursion to me or give me a starting point?
public static double squareRootRec (double num, double guess) {
if(num == 1) return 1;
}
-
Re: Creating recursion method to use Newton's method for square roots
Instead of using a while loop, you need to allow the method to call itself to repeat the part of code you are repeating in your loop. Get your logic right, or you could get a StackOverflow error - The recursion method has to know when to stop. That's not so hard though, you just need to give it a condition whereby it can decide if it needs to recurse again or stop.
you need something like this:
Java Code:public static double squareRoot(double num, double guess) { boolean continue = ... // the condition to continue if (continue) { ... // make one step squareRoot(value1, value2); // recurse } // otherwise let it end return resultValue; }
- 03-23-2012, 05:53 AM #3
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,068
- Blog Entries
- 3
- Rep Power
- 13
Re: Creating recursion method to use Newton's method for square roots
I'd like to add two things. Generally when doing recursion, you should not have loops (this is not to say you can't, but excessive loops should lead you to consider a different approach).
Also, check this out: Example: Square Roots by Newton's Method
It uses lisp, which may be confusing but the idea here should be quite clear.
Similar Threads
-
Bisection Method to find Square and Cube Roots
By tecnicamente in forum New To JavaReplies: 2Last Post: 05-07-2011, 02:03 AM -
Solution for Newton-Raphson method
By kienph2004 in forum Advanced JavaReplies: 1Last Post: 10-29-2009, 07:49 AM -
Display Square Roots
By hypes057 in forum New To JavaReplies: 8Last Post: 08-25-2009, 11:34 AM -
Creating a New Method for Square Root Loop
By SapphireSpark in forum New To JavaReplies: 14Last Post: 02-25-2009, 02:21 PM -
Pls Help me for Newton-Raphson method by Java
By kienph2004 in forum Advanced JavaReplies: 3Last Post: 08-13-2008, 06:07 PM
Bookmarks