(不准放到金融工程那种不伦不类的地方) Code: 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; }
呵呵 是sqrt() C++环境下比sqrt()运算快4倍,用了牛顿迭代 亮点在于牛顿迭代和0x5f3759df 神秘的0x5f3759df出奇地接近最终解,更有趣的是,这段源码是反编译Quake 3游戏的一个函数得到的。据说,原创者为Quake 3的程序员John Carmack,或者是前Nvidia员工Gary Tarolli。 想当初上高中玩Quake3的时候,一直想找快速算方根的方法,没想到答案居然在一个对战游戏里。
據說是源自MIT,SICP一書也提到了這個。 http://games.solidot.org/article.pl?sid=06/12/04/0210205 http://blog.ijliao.info/archives/2006/12/04/2739/ http://home.pipeline.com/~hbaker1/hakmem/hakmem.html http://www.cl.cam.ac.uk/~am21/hakmemc.html