不使用库函数sqrt实现求一个数的平方根
二分法:
double mysqrt(double a) { if(a == 0 ) return 0; double precision = 1.0e-7, start = 0, end = a; if(a < 1) end = 1; while(end - start > precision) { double mid = (start + end) / 2; if( mid == a / mid) return mid; else if(mid > a/mid) end = mid; else start = mid; } return (start + end)/2; }
牛顿迭代:
/* 牛顿法求解 */ #define E 0.0000001 double newton(double number, int *count) //*count 可统计出迭代次数 { double x0 = number; double x1; if(x0<E)return 0; while(true) { (*count)++; x1 = -(x0*x0 - number) / (2 * x0) + x0; //x1 = (x0*x0 + number) / (2 * x0) if(x1 * x1 - number <= E && x1 * x1 - number >= -E) return x1; x0 = x1; } return 0; }