public class demo { public static void main(String[] args) { System.out.println("———— 二分法计算根号 ————"); double result_a = math_Method.mathematicalDichotomy(99999999L, 1, 2, 2); double result_b = math_Method.mathematicalDichotomy(99999999L, 2, 3, 8); if (result_a + result_a - result_b >= 0 || result_b - (result_a + result_a) <= 0) { System.out.println("综上 : √2 + √2 = √8"); } else { System.out.println("综上 : √2 + √2 ≠ √8"); } System.out.println("—— 牛顿迭代法计算根号 ——"); double result_c = math_Method.Newton_iterative_method(2, 99999999L); double result_d = math_Method.Newton_iterative_method(8, 99999999L); if (result_c + result_c - result_d >= 0 || result_d - (result_c + result_c) <= 0) { System.out.println("综上 : √2 + √2 = √8"); } else { System.out.println("综上 : √2 + √2 ≠ √8"); } } } class math_Method { public static double mathematicalDichotomy( long times, double low, double high, double number_Of_Required__square) { double average = 0, sum; for (int x = 0; x < times; x++) { average = (low + high) / 2; sum = average * average; if (sum > number_Of_Required__square) high = average; else low = average; } System.out.println("√" + number_Of_Required__square + " = " + average); return average; } public static double Newton_iterative_method(double number_Of_Required__square, long times) { /* 牛顿迭代公式:X(n+1)=(X(n)+a/X(n))/2 */ double X1 = number_Of_Required__square / 2; double X_n_jia_1 = 0; for (int i = 0; i <= times; i++) { X_n_jia_1 = (X1 + number_Of_Required__square / X1) / 2; if (X_n_jia_1 - X1 >= 0 & X_n_jia_1 - X1 <= 0.00000001) { System.out.println("√" + number_Of_Required__square + " = " + X_n_jia_1); break; } else if (X_n_jia_1 - X1 <= 0 & X_n_jia_1 - X1 >= 0.00000001) { System.out.println("√" + number_Of_Required__square + " = " + X_n_jia_1); break; } else { X1 = X_n_jia_1; } } return X_n_jia_1; } }