我编写了这个程序,用于显示找到平方根的牛顿方法,然后运行数学函数找到平方根并打印出它们。数学部分运行良好,但我创建的循环没有为牛顿方法提供正确的平方根。有任何想法吗?提前谢谢。
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);
}
}
答案 0 :(得分:1)
反转循环条件。你希望在absolutex
大于epsilon时循环,而不是在它变小的时候循环。当它足够小时,你想停止。
do {
} while(absolutex > .000001);
答案 1 :(得分:0)
看起来像数学部分需要很少的调整,循环条件也是如此。在这里尝试,它的工作原理
package newton_sqrt;
import java.util.Scanner;
public class Newton_sqrt {
public static void main(String[] args) {
// TODO code application logic here
double guess, new_guess = 0, 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 = last_guess - (last_guess*last_guess-n) / (2*last_guess);
x = Math.abs(last_guess - new_guess);
if (x < .000001) {
break ;
} else {
last_guess = new_guess;
}
} while (n >= .00);
System.out.println("Newton = " + new_guess);
double mth = Math.sqrt(n);
System.out.println("Math.sqrt = " + mth);
}
}