求平方根的两种方法

1. Babylonian method
基本思路是,假定求S的平方根,如果x是S的一个 overestimate, 那么S/x是S的一个underestimate..

然后取平均数逼近。。

double sqrt1(double a)
{
	double x = 1.0;
	while( x *x -a > 0.00001 || x *x -a < -0.00001)
	{
		double y  = (x + a/x) / 2;
		x = y;
	}

	return x;
}

2. 二分法:

double sqrt2(double a)
{
        double start = 0.0;
        double end = a;
        if( a < 1)
        {
                start = a;
                end = 1.0;
        }
        double sqrt;
        while( start <= end)
        {
                double mid = (start + end) / 2;
                sqrt = mid;
                if( mid * mid - a <= 0.00001 &&  mid * mid - a >=  -0.00001 )
                {
                        break;
                }

                else if( mid * mid  -a > 0.00001)
                {
                        end = mid;
                }
                else
                {
                        start = mid;
                }
        }

        return sqrt;
}

https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method

你可能感兴趣的:(求平方根的两种方法)