如何使两个后续迭代的差异成为JAVA中的一个条件

时间:2015-10-24 20:49:14

标签: java loops for-loop difference

一旦两次后续迭代的差异低于某个数字,我试图终止一个循环。

public static double squareRoot(double desiredRoot){
        double answer = 0;
        double estimate = desiredRoot/2;
        double oneCloser;
        for (int i = 0; i <= 100000; i++){
            oneCloser = (estimate + desiredRoot/estimate)/2;
            estimate = oneCloser;
            if ( Math.abs(oneCloser(i)-oneCloser(i-1))> 0.0001){ // here is my problem
                continue;
            }
            answer = estimate;
        }
        return answer;
    }

此外,我的循环运行方式是否比使用i&lt; 10000(大数字)。

非常感谢!

埃里克

2 个答案:

答案 0 :(得分:0)

根据this article

public static double squareRoot(double desiredRoot){
        double answer = 0;
        double estimate = desiredRoot/2;
        double oneCloser;
        for (int i = 0; i <= 100000; i++){

            double temp = desiredRoot/estimate
            if ( Math.abs(temp-estimate)> 0.0001){ // here is my problem
                break;
            }
            estimate = (estimate + desiredRoot/estimate)/2;
        }
        return estimate;
    }

使用for循环并不能保证这会对Math.abs(temp-estimate)> 0.0001的要求提出正确的答案。但我们肯定知道这段代码肯定会完成。

我们也可以使用while循环。但是没有时间保证。

 public static double squareRoot(double desiredRoot){

            double answer = 0;
            double estimate = desiredRoot/2;
            double oneCloser;
            boolean correct = false;
            while (correct){

                double temp = desiredRoot/estimate
                if ( Math.abs(temp-estimate)> 0.0001){ // here is my problem
                    correct = true;
                }
                estimate = (estimate + desiredRoot/estimate)/2;
            }
            return estimate;
        }
  

警告:尚未测试此代码,只是在编辑视图中写道

答案 1 :(得分:0)

我认为最简单的方法是将您的逻辑置于do {} while();循环中,这将使您的循环运行1次迭代,这将设置先前的值并计算1次额外的迭代。

public static double squareRoot(double desiredRoot) {
    double previousEst;
    double currentEst = desiredRoot/2;
    do {
        // store our previous value for reference in the loop condition.
        previousEst = currentEst;
        // calculate the new estimate based on the current value.
        currentEst = (currentEst + desiredRoot/currentEst)/2;
    } while(Math.abs(currentEst - previousEst) > 0.0001); // keep going until we have reached a very small deviation.

    // return our estimate
    return currentEst;
}