《雷神之锤III》里求平方根的函数

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;
}

QuakeIII是卡马克的杰作之一。在有的CPU上,这个函数比普通的(float)(1.0/sqrt(x)快4倍!快的原因之一是用了一个神秘常数,0x5f3759df。普渡大学的Chris Lomont在一篇论文里讨论了这个常数的意义,尝试用严格的方法推导出这个常数(他还提到有人认为这个函数是在NVidia工作过的Gary Tarolli写的)。Chris推出的常数是0x5f37642f),和Q_rsqrt里的稍有不同,而且实际表现也稍有不如。

你可能感兴趣的:(函数,职场,休闲)