我已经创建了一个有效的递归巴比伦平方根方法,但我想加入一个错误。我希望当测试数为+或-真实平方根的误差时程序停止。在这种情况下,程序将停止在 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 语句以检查数字是否在 targetnum-error
和 targetnum+error
范围内:
public static void babyRoot(double num , double err)
{
testnum = 0.5 * (testnum + (targetnum / testnum));
System.out.println("Test number equals: " + testnum);
if ((testnum >= (Math.sqrt(targetnum) - err)) &&
(testnum <= (Math.sqrt(targetnum) + err)))
System.out.println("The correct square root is: " + testnum);
else
babyRoot(testnum);
}
关于java - 工作递归巴比伦平方根,需要合并一个错误。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42376445/