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:

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;

}

It doesn't have to look exactly like that, but the idea is that you have a method which calls itself instead of using a while loop.

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.