gpt4 book ai didi

java - stackoverflow错误递归平方根

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:06 25 4
gpt4 key购买 nike

运行程序时出现 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 是什么?是的,但无论如何,我都会指出你遇到问题的地方。对于递归计算,下一个估计值的计算如下:

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

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

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

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

关于java - stackoverflow错误递归平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com