给定以IEEE 754浮点格式存储的32位浮点数x,找到x的反平方根,即x -1/2 。
一个简单的解决方案是进行浮点运算。以下是示例函数。
#include
#include
using namespace std;
float InverseSquareRoot(float x)
{
return 1/sqrt(x);
}
int main()
{
cout << InverseSquareRoot(0.5) << endl;
cout << InverseSquareRoot(3.6) << endl;
cout << InverseSquareRoot(1.0) << endl;
return 0;
}
输出:
1.41421
0.527046
1
以下是基于此的一种快速而有趣的方法。有关详细说明,请参见此内容。
#include
using namespace std;
// This is fairly tricky and complex process. For details, see
// http://en.wikipedia.org/wiki/Fast_inverse_square_root
float InverseSquareRoot(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759d5 - (i >> 1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
int main()
{
cout << InverseSquareRoot(0.5) << endl;
cout << InverseSquareRoot(3.6) << endl;
cout << InverseSquareRoot(1.0) << endl;
return 0;
}
输出:
1.41386
0.526715
0.998307
来源:
http://en.wikipedia.org/wiki/Fast_inverse_square_root