我编写了此程序,以展示牛顿方法求平方根,然后运行数学函数找到该平方根并将它们都打印出来。数学部分运行良好,但是我创建的循环没有为牛顿方法提供正确的平方根。有任何想法吗?提前致谢。

package newton_sqrt;

import java.util.Scanner;

public class Newton_sqrt {

    public static void main(String[] args) {

        double guess, new_guess, last_guess, accuracy, n, x, absolutex;

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter in N for Newton: ");
        n = keyboard.nextDouble();
        last_guess = n / 2;
        do {
            new_guess = ((n/last_guess) + last_guess)/2;
            x = new_guess - last_guess;
            if(x>=0)
                absolutex=x;
            else
            absolutex=-x;
        } while(absolutex < .000001);
        System.out.println("Newton = " +new_guess);
        double mth = Math.sqrt(n);
        System.out.println("Math.sqrt = " +mth);
    }
}

最佳答案

反转循环条件。您想在absolutex大于epsilon而不是较小的时候循环。您想停下来的时候停下来。

do {
} while(absolutex > .000001);

09-28 04:37