快速平方根倒数算法

算法核心思想提炼:

1、求根号转化为求对数。
2、用直线近似对数曲线。
3、找到浮点数二进制表示和其对数之间的关系。
4、利用3找的关系对浮点数进行线性运算即可得到结果的近似值。
5、使用牛顿迭代法优化近似值,减小误差。

 背景介绍:

2005年,id公司发布了《雷神之锤3:竞技场》的源代码,在源代码中,游戏粉丝们找到了一个算法,十分巧妙,很快出名了,该算法的唯一用途是计算平方根的倒数

  f(x) = \frac{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 hack
    i  = 0x5f3759df - ( i >> 1 );              // what the fuck?
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );  // 1st iteration 
 // y  =

你可能感兴趣的:(算法)