# 第六章第二十二题（数学：平方根的近似求法）(Math: approximate the square root) - 编程练习题答案

**6.22（数学：平方根的近似求法）有几种实现Math类中sqrt方法的技术。其中一个称为巴比伦法。它通过使用下面的公式反复计算近似地得到一个数字n的平方根：

nextGuess = (lastGuess + n / lastGuess) / 2

public static double sqrt(long n)

**6.22(Math: approximate the square root) There are several techniques for implementing the sqrt method in the Math class. One such technique is known as the Babylonian method. It approximates the square root of a number, n, by repeatedly performing the calculation using the following formula:

nextGuess = (lastGuess + n / lastGuess) / 2

When nextGuess and lastGuess are almost identical, nextGuess is the approximated square root. The initial guess can be any positive value (e.g., 1). This value will be the starting value for lastGuess. If the difference between nextGuess and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is the approximated square root of n. If not, nextGuess becomes lastGuess and the approximation process continues. Implement the following method that returns the square root of n:

public static double sqrt(long n)

``````public class Ans6_22_page202 {
public static void main(String[] args) {
System.out.println(sqrt(2));
}
public static double sqrt(long n) {
double Guess;
double nextGuess = 1;
do {
Guess = nextGuess;
nextGuess = (Guess + n / Guess) / 2;
} while (Guess - nextGuess >= 0.0001 || nextGuess - Guess >= 0.0001);
return nextGuess;
}
}``````