当前位置:网站首页>Application of binary search -- finding the square root sqrt of a number

Application of binary search -- finding the square root sqrt of a number

2022-06-12 13:24:00 shlyyy


One 、 Two points search

Binary search algorithm

Two 、 Code

#include <stdio.h>
#include <math.h>

#define PRECISION 0.0000001

double Sqrt(double n)
{
    
	double dblRet = 0.0;

	double dblLow = 0.0;
	double dblHigh = n;
	double dblMiddle = 0.0;


	//  Determine the minimum integer range of the current number 
	/*double i = 0; while (i <= n) { if (i * i == n) { return i; } if (i * i > n) { break; } i = i + 1.0; } dblHigh = i;*/

	while (dblLow <= dblHigh)
	{
    
		dblMiddle = dblLow + (dblHigh - dblLow) / 2;

		//  The judgment that two floating-point numbers are equal , Here is judgment (dblMiddle^2 == n)
		if ((dblMiddle * dblMiddle - n < (PRECISION))
			&& (dblMiddle * dblMiddle - n > -(PRECISION)))
		{
    
			dblRet = dblMiddle;
			break;
		}
		else if (dblMiddle * dblMiddle > n)
		{
    
			dblHigh = dblMiddle - PRECISION / 1000;   //  The smaller the value added or decreased here, the more accurate 
		}
		else if (dblMiddle * dblMiddle < n)
		{
    
			dblLow = dblMiddle + PRECISION / 1000;
		}

	}

	return dblRet;
}


int main()
{
    
	double n = 0.0;

	int i = 0;
	for (i = 0; i < 100; i++)
	{
    
		printf("Sqrt(%-02d)=%0.6lf \t math:sqrt(%-02d)=%0.6lf\r\n", i, Sqrt(i), i, sqrt(i));
	}

	getchar();
	return 0;
}

3、 ... and 、 Running results

 Square root test


原网站

版权声明
本文为[shlyyy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010516524023.html