# 计算机与数学 —— 雷神之锤3源码中的快速逆平方根算法

## 源码

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



## 单精度浮点数

x = 2 e x ( 1 + m x ) x = 2^{e_{x}} (1+m_{x})

I x = E X L + M x = L ( e x + B + m x ) Ix = E_XL + M_x=L(e_x+B+m_x)

## 牛顿法

y − f ( x 0 ) = f ′ ( x 0 ) ( x − x 0 ) y - f(x_0) = f'(x_0)(x - x_0)

x i + 1 = x i − f ( x i ) f ′ ( x i ) x_{i+1} = x_{i} - \dfrac{f(x_i)}{f'(x_i)}

g ( x ) = f ( x ) f ′ ( x ) g(x) = \dfrac{f(x)}{f'(x)}

ϵ i = x i − r \epsilon_i = x_i - r

ϵ i + 1 = ϵ i − g ( x i ) \epsilon_{i+1} = \epsilon_i - g(x_i)

## 算法分析

y = 1 x y = \dfrac{1}{\sqrt{x}}

f ( y ) = 1 y 2 − x = 0 f(y) = \dfrac{1}{y^2} - x = 0

y n + 1 = y n ( 3 − x y n 2 ) 2 y_{n+1} = \dfrac{y_n(3 - xy_n^2)}{2}

log ⁡ 2 y = − 1 2 log ⁡ 2 ( 1 + m x ) \log_{2}{y} = -\dfrac{1}{2}\log_{2}{(1+m_x)}

log ⁡ 2 ( 1 + m x ) ≈ m x + σ \log_2(1+m_x)\approx m_x + \sigma

L log ⁡ 2 x + L ( B − σ ) L\log_2{x}+L(B-\sigma)

I y ≈ 3 2 L ( B − σ ) − 1 2 I x I_y\approx \dfrac{3}{2}L(B-\sigma)-\dfrac{1}{2}I_x

i = 0x5f3759df - ( i >> 1 );


3 2 L ( B − σ ) = 0 x 5 f 3759 d f \dfrac{3}{2}L(B-\sigma) = 0x5f3759df

<全文完>

09-09 992
01-10 1205
09-13 1万+
07-26 5511
08-22 2077
10-29 1294
01-10
12-03 619
01-12 237
11-21