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

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

nextGuess = (lastGuess + n / lastGuess) / 2

当nextGuess和lastGuess几乎相同时,nextGuess就是平方根的近似值。最初的猜测值可以是任意一个正值(例如1)。这个值就是lastGuess的初始值。如果nextGuess和lastGuess的差小于很小的数,比如0.0001,就可以认为nextGuess是n的平方根的近似值;否则,nextGuess就成为lastGuess,求近似值的过程继续执行。实现下面的方法,返回n的平方根。

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;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注