[Functions]D. Liang 5.23 Approximating the square root.c

Description

Implementing the sqrt function. The square root of a number n, can be approximated by repeated performing a 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 will be the starting value of lastGuess. If the difference between nextGuess and lastGuess is less than a very small number e (such as 0.0001), you can claim that nextGuess is the approximated square root of n.

Input

The first line is a positive integer t (0<t<=20) for the number of test cases.
Each test case contains an double value n (0<=n<=100000) and a double value e (such as 0.001).

Output

For each test case, output the square root of n in one line.
You should set the precision to 8 and fixed;

Sample Input

2
4 0.001
2 0.01

Sample Output

2.00000009
1.41421569

Related knowledge
The dichotomy is the method of bisection. Let [ a , b a,b ] be the closed interval of R R ,the successive dichotomy is to create the following interval sequence ([ a n , b n a_n,b_n ]): a 0 = a , b 0 = b a_0 = a, b_0 = b , and for any natural number n n , [ a n + 1 , b n + 1 a_n+1,b_n+1 ] or equal to [ a n , c n a_n,c_n ], or equal to [ c n , b n c_n, b_n ], where cn is the middle point of [ a n , b n a_n,b_n ].

The solution code is as follows:

//   Date:2020/4/3
//   Author:xiezhg5
#include <stdio.h>
#include <math.h>       //调用fabs绝对值函数 
double Aqrt(double n,double i);  //Aqrt函数声明
int main(void) {
	int m;
	scanf("%ld",&m);
	while(m>0) {
		double n,i;
		scanf("%lf %lf",&n,&i);
		printf("%.8lf\n",Aqrt(n,i));
		m--;   //while条件判断的语句有点让人耳目一新
	}
	return 0;
}
double Aqrt(double n,double i) {
	double nextGuess = n, lastGuess = 1;     //传入值到Aqrt函数中
	while(fabs(nextGuess-lastGuess) >= i) {  //题目的要求的误差范围
		//二分法的核心算法,题目也给了公式
		lastGuess = nextGuess;
		nextGuess = (lastGuess + n / lastGuess) / 2;
	}
	return nextGuess;
}
发布了165 篇原创文章 · 获赞 124 · 访问量 5626

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/105288033