三种方法分别是二分法、牛顿法和卡马克算法(本质上也是牛顿法,初始值取得很巧妙)。代码如下:
#include<iostream>
using namespace std;
double sqrt_math1(double x) { //二分法,不断取中间值进行迭代
if (x < 0) return -1;
double low = (x >= 1 ? 1 : x), high = (x >= 1 ? x : 1), mid = (low + high) / 2;
while (abs(mid*mid - x) > 0.000001) {
if (mid*mid > x) high = mid;
else low = mid;
mid = (low + high) / 2;
}
return mid;
}
double sqrt_math2(double x) { //牛顿法,速度比二分法快
if (x < 0) return -1;
double pre = x, tem = (pre + x / pre) / 2;
while (abs(tem*tem - x) > 0.000001) {
tem = (tem + x / tem) / 2;
}
return tem;
}
float sqrt_math3(float x) { //卡马克快速平方根算法(游戏编程经典算法),比牛顿法快
if (x < 0) return -1;
float xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating VALUE
i = 0x5f375a86 - (i >> 1); // gives initial guess y0
x = *(float*)&i; // convert bits BACK to float
x = x*(1.5f - xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(1.5f - xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(1.5f - xhalf*x*x); // Newton step, repeating increases accuracy
return 1 / x;
}
int main() {
double x;
cout << "Input the number:";
while (cin >> x) {
cout << sqrt_math1(x) << endl;
cout << sqrt_math2(x) << endl;
cout << sqrt_math3(x) << endl;
}
system("pause");
return 0;
}