Sqrt
牛顿迭代法
1 double NewtonMethod(double fToBeSqrted) 2 { 3 double x = 1.0; 4 while(abs(x*x-fToBeSqrted) > 1e-5) 5 { 6 x = (x+fToBeSqrted/x)/2; 7 } 8 9 return x; 10 }
二分法
1 float get_sqrt(float x) 2 { 3 float low=0, up=x, mid, now; 4 mid=(low+up)/2; 5 do 6 { 7 now=mid; //**now保存上一次计算的值 8 if(mid*mid<x) //**mid偏小,右移 9 { 10 low=mid; 11 } 12 else //**mid偏大,左移 13 { 14 up=mid; 15 } 16 mid=(low+up)/2; 17 }while(abs(mid-now)>eps); //**两次计算的误差小于eps,mid即为所求值 18 return mid; 19 }