浮点数快速开平方

来源:互联网 发布:新手入门算法推荐书籍 编辑:程序博客网 时间:2024/04/30 05:12

//
// Carmack在QUAKE3中使用的计算平方根的函数
//
float __stdcall CarmSqrt(float x)
{ union
 { int intPart;
  float floatPart;
 } cv1,cv2;
 cv1.floatPart = x;
 cv2.floatPart = x;
 cv1.intPart = 0x1FBCF800 + (cv1.intPart >> 1);
 cv2.intPart = 0x5f3759df - (cv2.intPart >> 1);
 return 0.5f*(cv1.floatPart + (x * cv2.floatPart));
};
//
// 计算参数x的平方根的倒数
//magic=0x5f3759df,0x5f375a86,0x5f37642f
float __stdcall 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); // 牛顿迭代法
 return x;
};

double __stdcall InvSqrt (double x)
{ double xhalf = 0.5f*x;
 __int64 i = *(__int64*)&x;
 i = 0x5fe6ec85e7de30da - (i >> 1); // 计算第一个近似根
 x = *(double*)&i;
 x = x*(1.5f - xhalf*x*x); // 牛顿迭代法
 return x;
};

原创粉丝点击