求平方根(根号n)的两种算法——二分法和牛顿迭代

面试阿里口碑的时候遇到了这个问题,这里做个笔记

1.二分法

#define eps 0.00001
float SqrtByDichotomy(float n)
{
	if (n < 0)
	{
		return -1.0;
	}
	else
	{
		float low, up, mid, last;
		low = 0, up = (n>=1?n:1);
		mid = (low + up) / 2;
		do {
			if (mid*mid>n)
				up = mid;
			else
				low = mid;
			mid = (up+low)/2;
		} while (fabsf(mid - last) > eps);
		return mid;
	
	}
}

2.牛顿迭代法

double Sqr(double a) {
	double x = a, y = 0.0;
	while (fabs(x - y) > 0.00001) {
		y = x;
		x = 0.5*(x + a / x);
	}
	return x;
}

你可能感兴趣的:(面试经验)