简体   繁体   中英

stackoverflow error recursion square root

I am getting a stackoverflow error when I run my program. I am quite knew to java and I could use a bit of advice.

Any help is appreciated!

public class ApproxSquareRoot {

public static float sqrRootRec(float number, float approx, float tol) {
    if((Math.abs((Math.pow(approx,2) - number))<= tol*number)) {
       return approx;
    } else
       return sqrRootRec(number, (approx*approx + number/(2*approx)),tol);


}

public static float sqrRoot(float number, float approx, float tol) {

     while (Math.abs((Math.pow(approx,2) - number))<= tol*number)
     approx = (approx*approx + number)/(approx + approx);
     return approx;
}

}

.

Input number: 43
Input approx: 2.5
Input tol: .1
Output with number = 43.0 approx = 2.5 tolerance = 0.1
Exception in thread "main" java.lang.StackOverflowError

As noted in the comments, please research what a StackOverflowError is, but regardless of that, I shall point out where you are getting a problem. For your recursive calculation, the next estimate is calculated as follows:

return sqrRootRec(number, (approx*approx + number/(2*approx)),tol);

However, for the iterative case, there is:

approx = (approx*approx + number)/(approx + approx);

Note that these two approximations are not equal, so although I haven't checked the maths, if you make your sqrRootRec function use the second form, it should solve the StackOverflowError .

In your iterative function, the next iteration becomes:

(approx*approx + number)/(approx + approx)

In your recursive function, it becomes:

(approx*approx + number/(2*approx))

As you see, the parentheses are different. Your recursive function can be written as:

(approx*approx + (number/(2*approx)))

For the iterative function, after one iteration the value becomes:

(2.5 * 2.5 + 43) / (2.5 + 2.5) = 9.85

But for your recursive function it is:

(2.5 * 2.5 + (43 / (2 * 2.5))) = 14.85

That's quite different. Fix the location of the parentheses [the ( and ) ] and you'll be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM