计算平方根(牛顿迭代法)

参考网友的博文:https://blog.csdn.net/w20810/article/details/49030961

发现有两种实现办法,如下:


#include 
#include 
#include 

using namespace std;

double sqrt1(double x)
{
	double k=x;
	while(k*k-x>1e-9)
		k=0.5*(k+x/k);
	return k;
}

double sqrt2(double n)
 {
        double err = 1e-9;
        double t = n;
        while (fabs(t - n/t) > err*t)
            t = (n/t + t)/2;
        return t;
}

int main()
{
	printf("enter the val of sqrt:\n");
	clock_t start,finish;
	double duration;
	start = clock();
	printf("sqrt(c)=%.91f\n",sqrt1(11316));
	finish = clock();
	duration = (double)(finish-start)/CLOCKS_PER_SEC;
	printf("duration = %.91f\n",duration);
	start = clock();
	printf("sqrt(c)=%.91f\n",sqrt2(11316));
	finish = clock();
	duration = (double)(finish-start)/CLOCKS_PER_SEC;
	printf("duration = %.91f\n",duration);
	system("pause");
	return 0;
}

两个办法,我实验两种方法分别计算的是11316和1316的平方根,前者是sqrt2使用时间较短,后缀是sqrt1使用时间较短。两者的计算值差别不大。

表明,在同一精度同一算法下,两种实现方式各有优劣。

你可能感兴趣的:(c++,算法)