71 lines
1.9 KiB
TeX
Raw Normal View History

2025-01-22 12:37:56 -08:00
\section{The Fast Inverse Square Root}
The following code is present in \textit{Quake III Arena} (1999):
\lstset{
breaklines=false,
numbersep=5pt,
xrightmargin=0in
}
\begin{lstlisting}[language=C]
float Q_rsqrt( float number ) {
long i = * ( long * ) &number;
i = 0x5f3759df - ( i >> 1 );
return * ( float * ) &i;
}
\end{lstlisting}
It defines a method \texttt{Q\_rsqrt} that consumes a float named \texttt{number} and quickly approximates its inverse
square root (in other words, \texttt{Q\_rsqrt} computes $1/\sqrt{\texttt{number}}$).
\vspace{8mm}
If we rewrite this using the notation we're familiar with, we get the following:
\begin{equation*}
\frac{1}{\sqrt{n_f}} \approx \kappa - (n_i \div 2)
\end{equation*}
Where $\kappa$ is the magic constant $6240089$ (which is \texttt{0x5f3759df} in hexadecimal)
\problem{}
Find the exact value of $\kappa$ in terms of $\varepsilon$. \par
\hint{Remember that $\varepsilon$ is the correction term in the approximation $\log_2(1 + a) = a + \varepsilon$.}
\problem{}
Rewrite $\log_2(1 / \sqrt{x})$ in terms of $\log_2{x}$.
\begin{solution}
Say $g_f = \frac{1}{\sqrt{n_f}}$---that is, $g_f$ is the value we want to compute. \par
Then:
\begin{align*}
\log_2(g_f)
&=\log_2(\frac{1}{\sqrt{n_f}}) \\
&=\frac{-1}{2}\log_2(n_f) \\
&=\frac{-1}{2}\left( \frac{n_i}{2^{23}} + \varepsilon - 127 \right)
\end{align*}
But we also know that
\begin{align*}
\log_2(g_f)
&=\frac{g_i}{2^{23}} + \varepsilon - 127
\end{align*}
So,
\begin{align*}
\frac{g_i}{2^{23}} + \varepsilon - 127
&=\frac{-1}{2}\left( \frac{n_i}{2^{23}} + \varepsilon - 127 \right) \\
\frac{g_i}{2^{23}}
&=\frac{-1}{2}\left( \frac{n_i}{2^{23}} \right) + \frac{3}{2}(\varepsilon - 127) \\
g_i
&=\frac{-1}{2}\left(n_i \right) + 2^{23}\frac{3}{2}(\varepsilon - 127) \\
&=2^{23}\frac{3}{2}(\varepsilon - 127) - \frac{n_i}{2}
\end{align*}
thus, $\kappa = 2^{23}\frac{3}{2}(\varepsilon - 127)$.
\end{solution}
\pagebreak