前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >第六章第二十二题(数学:平方根的近似求法)(Math: approximate the square root) - 编程练习题答案

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

作者头像
无刺鱼
发布2022-03-29 13:10:37
2130
发布2022-03-29 13:10:37
举报
文章被收录于专栏:许唯宇

**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)

下面是参考答案代码:

代码语言:javascript
复制
// https://cn.fankuiba.com

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;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/05/12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档