【发布时间】:2017-02-21 19:39:44
【问题描述】:
我创建了一个有效的递归巴比伦平方根方法,但我想加入一个错误。我希望程序在测试数为 + 或 - 实平方根的错误时停止。在这种情况下,程序将在 5.015.... 处停止,因为 5.015 在实数平方根 (5) 的 0.1 范围内。
public class BabyRoot {
private static double testnum = 0;
private static double targetnum = 0;
private static double error = 0;
public static void babyRoot(double num) {
testnum = 0.5 * (testnum + (targetnum / testnum));
System.out.println("Test number equals: " + testnum);
if ((testnum * testnum) == targetnum)
System.out.println("The correct square root is: " + testnum);
else
babyRoot(testnum);
}
public static void main(String[] args) {
error = 0.1;
testnum = 25;
targetnum = testnum;
babyRoot(testnum);
}
}
输出:
Test number equals: 13.0
Test number equals: 7.461538461538462
Test number equals: 5.406026962727994
Test number equals: 5.015247601944898
Test number equals: 5.000023178253949
Test number equals: 5.000000000053722
Test number equals: 5.0
The correct square root is: 5.0
【问题讨论】:
-
好的,感谢您告诉我们。你有什么问题?这不仅仅是将两个数字相减、取绝对值(如果需要)并将其弹出到 if 语句中的简单问题吗?
-
您是否有理由不能将检查放入您的程序中?这似乎是一个相当简单的条件。
-
您确定要这样定义错误吗?在数值计算中,您并不总是有权获得现成的“真实”答案,因此通常错误值的使用方式不同(例如,两次连续迭代中的结果之间的差异,或者您进行反向计算时的差异)。
标签: java recursion square-root