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版)更多内容

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值