阅读The Tricks of the 3D Game Programming Gurus时,我遇到了这个用内联汇编编写的排序函数:
inline float FastSqrt(float Value)
{
float Result;
_asm
{
mov eax, Value
sub eax, 0x3F800000
sar eax, 1
add eax, 0x3F800000
mov Result, eax
}
return(Result);
}
这是实际平方根的近似值,但准确度足以满足我的需要。
这实际上是如何工作的?这是什么神奇的0x3F800000
价值?我们如何通过减法、旋转和加法来获得平方根?
下面是它在 C/C++ 代码中的样子:
inline float FastSqrt_C(float Value)
{
float Result;
long Magic = *((long *)&Value);
Magic -= 0x3F800000;
Magic >>= 1;
Magic += 0x3F800000;
Result = *((float *)&Magic);
return(Result);
}