2007年3月13日星期二

快速平方根算法

使用Mageic Number快速计算平方根和平方根的倒数,下面是JC的实现:
// 计算32位浮点数的平方根
float CarmSqrt(float x)
{
union{
int intPart;
float floatPart;
} convertor;
union{
int intPart;
float floatPart;
} convertor2;
convertor.floatPart = x;
convertor2.floatPart = x;
convertor.intPart = 0x1FBCF800
+ (convertor.intPart >> 1);
convertor2.intPart = 0x5f3759df
- (convertor2.intPart >> 1);
return 0.5f*(convertor.floatPart
+ (x * convertor2.floatPart));
}
// 计算32位浮点数的平方根的倒数
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);
return x;
}

Chris Lomot的演算和实验得出,用于该算法最佳的Magic Number是0x5f37a86(32位)和0x5fe6ec85e7de30da(64位)。

具体请参阅:友善之臂旅店

没有评论: