Quake III的代码里面找出来的一段飞速计算平方根的倒数的代码。算法是牛顿迭代法的无限逼近,亮点在标题的这个0x5f3759df,被称为“Magic Number”,这个东东让计算平方根比一般的牛顿逼近快了4倍。又据说,0x5f375a86这个数比0x5f3759df效率更高。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}

Read the rest of this entry »

如果您喜欢本站的内容,欢迎订阅我的RSS以获取本站最新资讯。

大中华局域网用户订阅地址:http://feed.casparant.com/

国际互联网用户订阅地址:http://feeds.casparant.com/casparant