简体   繁体   English

工作递归巴比伦平方根,需要包含一个错误。

[英]Working recursive babylonian square root, need to incorporate an error.

I have created a working recursive babylonian square root method but I would like to incorporate an error. 我创建了一个工作递归的巴比伦平方根方法,但我想合并一个错误。 I want for the program to stop when the test number is + or - the error for the real square root. 我希望程序在测试号为+或-时停止,以实平方根为准。 In this case, the program would stop at 5.015.... since 5.015 is within 0.1 of the real square root (5). 在这种情况下,程序将在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);
}

}

Output: 输出:

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

You need to change your if statement to check if the number is within the range of targetnum-error and targetnum+error : 您需要更改if语句,以检查数字是否在targetnum-errortargetnum+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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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