最近看到一篇文章介绍quake3中的一种快速开方算法,今天测试了一下,结果很奇怪,希望有人能够帮助我解惑。
quake3中求1/sqrt(x)的算法源代码如下(未作任何修改):
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
#ifndef Q3_VM
#ifdef __linux__
assert( !isnan(y) ); // bk010122 - FPE?
#endif
#endif
return y;
}
此算法关键在于0x5f3759df的原理,详细论述我没仔细看,论文在http://www.lomont.org/Math/Papers/2003/InvSqrt