Posted on 2010-06-30 02:03
魔のkyo 阅读(418)
评论(0) 编辑 收藏 引用
// 计算参数x的平方根的倒数
double InvSqrt(double number)
{
long long i;
double x2, y;
const double threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = *(long long*) &y;
i = 0x5fe6ec85e7de30dall - (i>>1);
y = *(double*) &i;
y = y * ( threehalfs-(x2*y*y)); //第一次牛顿迭代
y = y * ( threehalfs-(x2*y*y)); //第二次牛顿迭代
return 2*y;
}
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1); //计算第一个近似根
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x); //做一次牛顿迭代
//如果要精确点可以再做2次
return x;
}