zoukankan      html  css  js  c++  java
  • 第六章第二十二题(数学:平方根的近似求法)(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)

    下面是参考答案代码:

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

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

  • 相关阅读:
    hadoop学习摘要
    尝试加载 Oracle 客户端库时引发 BadImageFormatException。如果在安装 32 位 Oracle 客户端组件的情况下以 64 位模式运行,将出现此问题。
    sqlserver 2012 IDE中 Windows身份验证连接服务器报错 ,Login failed for user 'xxxAdministrator'. 原因: 找不到与提供的名称匹配的登录名。
    不重复随机数列生成算法
    异步和等待(async和await)
    mvc和mvvm的区别?
    Redis命令大全
    Java NIO 三大组件之 Buffer
    Java NIO 三大组件之 Channel
    Java NIO概述
  • 原文地址:https://www.cnblogs.com/in2013/p/12876691.html
Copyright © 2011-2022 走看看