【问题标题】:stackoverflow error recursion square rootstackoverflow错误递归平方根
【发布时间】:2016-03-16 11:32:25
【问题描述】:

我在运行程序时遇到 stackoverflow 错误。我对java非常了解,我可以使用一些建议。

感谢任何帮助!

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

【问题讨论】:

  • 你研究过StackOverflowError是什么吗?
  • 你可能得到了一个无限递归。
  • @TimBiegeleisen 我该如何解决这个问题.. 你能帮忙吗?
  • 检查下面的答案,因为它似乎在正确的轨道上。

标签: java recursion


【解决方案1】:

如 cmets 所述,请研究 StackOverflowError 是什么,但无论如何,我将指出您遇到问题的地方。对于您的递归计算,下一个估计值计算如下:

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

但是,对于迭代的情况,有:

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

请注意,这两个近似值不相等,所以虽然我没有检查数学,但如果你让你的 sqrRootRec 函数使用第二种形式,它应该解决 StackOverflowError

【讨论】:

    【解决方案2】:

    在您的迭代函数中,下一次迭代变为:

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

    在你的递归函数中,它变成:

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

    如您所见,括号是不同的。你的递归函数可以写成:

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

    对于迭代函数,经过一次迭代后,值变为:

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

    但对于您的递归函数,它是:

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

    那是完全不同的。修正括号的位置 [()] 就可以了。

    【讨论】:

    • 感谢您的解释!
    猜你喜欢
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    相关资源
    最近更新 更多