神奇的Invsqrt函数

 1 float InvSqrt(float x)  
 2 {  
 3     float xhalf = 0.5f*x;  
 4     int i = *(int*)&x;      // get bits for floating VALUE  
 5     i = 0x5f375a86- (i>>1); // gives initial guess y0  
 6     x = *(float*)&i;        // convert bits BACK to float  
 7     x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy  
 8     x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy  
 9     x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy  
10     return 1/x;  
11 }  

这个代码是求x^(-1/2),使用牛顿迭代法迭代求解,

神奇的是其效率精度比默认函数还要高。

其中神秘的0x5f375a86是迭代的初始值,理论上可以使任意值,从它开始向最终结果逼近。

通过枚举可以验证选择0x5f375a86的精度最高。

posted @ 2018-03-03 19:22  ArrogantL  阅读(855)  评论(0编辑  收藏  举报