# Fast inverse square root

Fast inverse square root, sometimes referred to as Fast InvSqrt or by the hexadecimal constant 0x5F3759DF, is an algorithm that estimates 1/√x {\textstyle {\frac {1}{\sqrt {x}}}}, the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number $x$ in IEEE 754 floating-point format. The algorithm is best known for its implementation in 1999 in Quake III Arena, a first-person shooter video game heavily based on 3D graphics. With subsequent hardware advancements, especially the x86 SSE instruction rsqrtss, this algorithm is not generally the best choice for modern computers, though it remains an interesting historical example.
The algorithm accepts a 32-bit floating-point number as the input and stores a halved value for later use. Then, treating the bits representing the floating-point number as a 32-bit integer, a logical shift right by one bit is performed and the result subtracted from the number 0x5F3759DF, which is a floating-point representation of an approximation of √(2$^{127}$){\textstyle {\sqrt {2^{127}}}}. This results in the first approximation of the inverse square root of the input. Treating the bits again as a floating-point number, it runs one iteration of Newton's method, yielding a more precise approximation.

## History

William Kahan and K.C. Ng at Berkeley wrote an unpublished paper in May 1986 describing how to calculate the square root using bit-fiddling techniques followed by Newton iterations. In the late 1980s, Cleve Moler at Ardent Computer learned about this technique and passed it along to his coworker Greg Walsh. Greg Walsh devised the now-famous constant and fast inverse square root algorithm. Gary Tarolli was consulting for Kubota, the company funding Ardent at the time, and likely brought the algorithm to 3dfx Interactive circa 1994.
Jim Blinn demonstrated a simple approximation of the inverse square root in a 1997 column for IEEE Computer Graphics and Applications. Reverse engineering of other contemporary 3D video games uncovered a variation of the algorithm in Activision's 1997 Interstate '76.
Quake III Arena, a first-person shooter video game, was released in 1999 by id Software and used the algorithm. Brian Hook may have brought the algorithm from 3dfx to id Software. A discussion of the code appeared on the Chinese developer forum CSDN in 2000, and Usenet and the gamedev.net forum spread the code widely in 2002 and 2003. Speculation arose as to who wrote the algorithm and how the constant was derived; some guessed John Carmack. Quake III's full source code was released at QuakeCon 2005, but provided no answers. The authorship question was resolved in 2006 when Greg Walsh, the original author, contacted Beyond3D after their speculation gained popularity on Slashdot.
In 2007 the algorithm was implemented in some dedicated hardware vertex shaders using field-programmable gate arrays (FPGA).

## Motivation

The inverse square root of a floating point number is used in digital signal processing to normalize a vector, scaling it to length 1 to produce a unit vector. For example, computer graphics programs use inverse square roots to compute angles of incidence and reflection for lighting and shading. 3D graphics programs must perform millions of these calculations every second to simulate lighting. When the code was developed in the early 1990s, most floating point processing power lagged the speed of integer processing. This was troublesome for 3D graphics programs before the advent of specialized hardware to handle transform and lighting. Computation of square roots usually depends upon many division operations, which for floating point numbers are computationally expensive. The fast inverse square generates a good approximation with only one division step.
The length of the vector is determined by calculating its Euclidean norm: the square root of the sum of squares of the vector components. When each component of the vector is divided by that length, the new vector will be a unit vector pointing in the same direction. In a 3D graphics program, all vectors are in three-dimensional space, so ${\boldsymbol {v}}$ would be a vector $(v_{1},v_{2},v_{3})$. Then,
    $\|{\boldsymbol {v}}\|={\sqrt {v_{1}^{2}+v_{2}^{2}+v_{3}^{2}}}$
is the Euclidean norm of the vector, and the normalized (unit) vector is
    ${\begin{aligned}{\boldsymbol {\hat {v}}}&={\frac {1}{\left\|{\boldsymbol {v}}\right\|}}{\boldsymbol {v}}\\&={\frac {1}{\sqrt {v_{1}^{2}+v_{2}^{2}+v_{3}^{2}}}}\,{\boldsymbol {v}},\end{aligned}}$
where the fraction term is the inverse square root of $v_{1}^{2}+v_{2}^{2}+v_{3}^{2}$.
At the time, floating-point division was generally expensive compared to multiplication; the fast inverse square root algorithm bypassed the division step, giving it its performance advantage.

## Overview of the code

The following C code is the fast inverse square root implementation from Quake III Arena, stripped of C preprocessor directives, but including the exact original comment text:
At the time, the general method to compute the inverse square root was to calculate an approximation for 1/√x {\textstyle {\frac {1}{\sqrt {x}}}}, then revise that approximation via another method until it came within an acceptable error range of the actual result. Common software methods in the early 1990s drew approximations from a lookup table. The key of the fast inverse square root was to directly compute an approximation by utilizing the structure of floating-point numbers, proving faster than table lookups. The algorithm was approximately four times faster than computing the square root with another method and calculating the reciprocal via floating-point division. The algorithm was designed with the IEEE 754-1985 32-bit floating-point specification in mind, but investigation from Chris Lomont showed that it could be implemented in other floating-point specifications.
The advantages in speed offered by the fast inverse square root trick came from treating the 32-bit floating-point word as an integer, then subtracting it from a "magic" constant, 0x5F3759DF. This integer subtraction and bit shift results in a bit pattern which, when re-defined as a floating-point number, is a rough approximation for the inverse square root of the number. One iteration of Newton's method is performed to gain some accuracy, and the code is finished. The algorithm generates reasonably accurate results using a unique first approximation for Newton's method; however, it is much slower and less accurate than using the SSE instruction rsqrtss on x86 processors also released in 1999.

### Worked example

As an example, the number $x=0.15625$ can be used to calculate 1/√x ≈2.52982{\textstyle {\frac {1}{\sqrt {x}}}\approx 2.52982}. The first steps of the algorithm are illustrated below:
Interpreting as IEEE 32-bit representation:
Reinterpreting this last bit pattern as a floating point number gives the approximation $y=2.61486$, which has an error of about 3.4%. After one iteration of Newton's method, the final result is $y=2.52549$, an error of only 0.17%.

### Avoiding undefined behavior

According to the C standard, reinterpreting a floating point value as an integer by casting then dereferencing the pointer to it is not valid (undefined behavior). Another way would be to place the floating point value in a union containing an additional 32-bit unsigned integer member, and accesses to that integer provides a bit level view of the contents of the floating point value.
For C++, however, type punning through a union is also undefined behavior. In modern C++, the recommended method for implementing this function's casts is through C++20's std::bit_cast. This also allows the function to work in constexpr context:

## Algorithm

The algorithm computes 1/√x {\textstyle {\frac {1}{\sqrt {x}}}} by performing the following steps:
* Alias the argument $x$ to an integer as a way to compute an approximation of the binary logarithm log$_2$⁡(x){\textstyle \log _{2}(x)}
* Use this approximation to compute an approximation of log$_2$⁡(1/√x)=−1/2 log$_2$⁡(x){\textstyle \log _{2}\left({\frac {1}{\sqrt {x}}}\right)=-{\frac {1}{2}}\log _{2}(x)}
* Alias back to a float, as a way to compute an approximation of the base-2 exponential
* Refine the approximation using a single iteration of Newton's method.

### Floating-point representation

Since this algorithm relies heavily on the bit-level representation of single-precision floating-point numbers, a short overview of this representation is provided here. To encode a non-zero real number $x$ as a single precision float, the first step is to write $x$ as a normalized binary number:
    ${\begin{aligned}x&=\pm 1.b_{1}b_{2}b_{3}\ldots \times 2^{e_{x}}\end{aligned}}$
where the exponent e$_x${\textstyle e_{x}} is an integer, and 1.b$_1$b$_2$b$_3$…{\textstyle 1.b_{1}b_{2}b_{3}\ldots } is the binary representation of the significand. Since the single bit before the point in the significand is always 1, it does not need be stored. The equation can be rewritten as:
    ${\begin{aligned}x&=(-1)^{S_{x}}\cdot 2^{e_{x}}(1+m_{x})\end{aligned}}$
where m$_x${\textstyle m_{x}} means 0.b$_1$b$_2$b$_3$…{\textstyle 0.b_{1}b_{2}b_{3}\ldots }, so m$_x$∈[0, 1){\textstyle m_{x}\in [0, 1)}. From this form, three unsigned integers are computed:
* S$_x${\textstyle S_{x}}, the "sign bit", is $0$ if $x$ is positive and $1$ negative or zero (1 bit)
* E$_x$=e$_x$+B{\textstyle E_{x}=e_{x}+B} is the "biased exponent", where $B=127$ is the "exponent bias" (8 bits)
* M$_x$=m$_x$×L{\textstyle M_{x}=m_{x}\times L}, where L=2$^{23}${\textstyle L=2^{23}} (23 bits)
Thus: e$_x$=E$_x$−B{\textstyle e_{x}=E_{x}-B} and m$_x$=M$_x$/L {\textstyle m_{x}={\frac {M_{x}}{L}}}.
These fields are then packed, left to right, into a 32-bit container.
As an example, consider again the number $x=0.15625=0.00101_{2}$. Normalizing $x$ yields:
    x=(−1)$^0$⋅2$^{−3}$(1+0.25)=+2$^{−3}$(1+0.25){\textstyle x=(-1)^{0}\cdot 2^{-3}(1+0.25)=+2^{-3}(1+0.25)}
and thus, the three unsigned integer fields are:
* $S=0$
* $E=-3+127=124=0111\ 1100_{2}$
* $M=0.25\times 2^{23}=2\ 097\ 152=0010\ 0000\ 0000\ 0000\ 0000\ 0000_{2}$
these fields are packed as shown in the figure below:
The number is represented in binary as: $I_{x}=S_{x}\cdot 2^{31}+E_{x}L+M_{x}$
Also, since this algorithm works on real numbers, √x{\textstyle {\sqrt {x}}} is only defined for x≥0{\textstyle x\geq 0}. The code thus assumes x≥0{\textstyle x\geq 0} and $S_{x}=0$.
The number, given to calculate the square root, could be rewritten as:
    I$_x$=E$_x$L+M$_x${\textstyle I_{x}=E_{x}L+M_{x}}
    x=(−1)$^0$⋅2$^{ex}$(1+m$_x$)=+2$^{ex}$(1+m$_x$){\textstyle x=(-1)^{0}\cdot 2^{e_{x}}(1+m_{x})=+2^{e_{x}}(1+m_{x})}

### Aliasing to an integer as an approximate logarithm

If 1/√x {\textstyle {\frac {1}{\sqrt {x}}}} were to be calculated without a computer or a calculator, a table of logarithms would be useful, together with the identity log$_b$⁡(1/√x)=log$_b$⁡(x$^{−1/2}$)=−1/2 log$_b$⁡(x){\textstyle \log _{b}\left({\frac {1}{\sqrt {x}}}\right)=\log _{b}\left(x^{-{\frac {1}{2}}}\right)=-{\frac {1}{2}}\log _{b}(x)}, which is valid for every base $b$. The fast inverse square root is based on this identity, and on the fact that aliasing a float32 to an integer gives a rough approximation of its logarithm. Here is how:
If $x$ is a positive normal number:
    $x=2^{e_{x}}(1+m_{x})$
then
    $\log _{2}(x)=e_{x}+\log _{2}(1+m_{x})$
and since $m_{x}\in [0,1)$, the logarithm on the right-hand side can be approximated by
    $\log _{2}(1+m_{x})\approx m_{x}+\sigma$
where $\sigma$ is a free parameter used to tune the approximation. For example, $\sigma =0$ yields exact results at both ends of the interval, while σ=1/2−(1+ln⁡(ln⁡(2)))/2ln⁡(2) ≈0.0430357{\textstyle \sigma ={\frac {1}{2}}-{\frac {1+\ln(\ln(2))}{2\ln(2)}}\approx 0.0430357} yields the optimal approximation (the best in the sense of the uniform norm of the error). However, this value is not used by the algorithm as it does not take subsequent steps into account.
Thus there is the approximation
    $\log _{2}(x)\approx e_{x}+m_{x}+\sigma .$
Interpreting the floating-point bit-pattern of $x$ as an integer $I_{x}$ yields
    ${\begin{aligned}I_{x}&=E_{x}L+M_{x}\\&=L(e_{x}+B+m_{x})\\&=L(e_{x}+m_{x}+\sigma +B-\sigma )\\&\approx L\log _{2}(x)+L(B-\sigma ).\end{aligned}}$
It then appears that $I_{x}$ is a scaled and shifted piecewise-linear approximation of $\log _{2}(x)$, as illustrated in the figure on the right. In other words, $\log _{2}(x)$ is approximated by
    $\log _{2}(x)\approx {\frac {I_{x}}{L}}-(B-\sigma ).$

### First approximation of the result

The calculation of y=1/√x {\textstyle y={\frac {1}{\sqrt {x}}}} is based on the identity
    $\log _{2}(y)=-{\tfrac {1}{2}}\log _{2}(x)$
Using the approximation of the logarithm above, applied to both $x$ and $y$, the above equation gives:
    ${\frac {I_{y}}{L}}-(B-\sigma )\approx -{\frac {1}{2}}\left({\frac {I_{x}}{L}}-(B-\sigma )\right)$
Thus, an approximation of $I_{y}$ is:
    $I_{y}\approx {\tfrac {3}{2}}L(B-\sigma )-{\tfrac {1}{2}}I_{x}$
which is written in the code as
    i = 0x5f3759df - ( i >> 1 );
The first term above is the magic number
    ${\tfrac {3}{2}}L(B-\sigma )={\mathtt {0x5F3759DF}}$
from which it can be inferred that $\sigma \approx 0.0450466$. The second term, ${\frac {1}{2}}I_{x}$, is calculated by shifting the bits of $I_{x}$ one position to the right.

### Newton's method

The number $y={\tfrac {1}{\sqrt {x}}}$ is a solution of the equation ${\tfrac {1}{y^{2}}}-x=0$. The approximation yielded by the earlier steps can be refined by using a root-finding method, a method that finds the zero of a function. The algorithm uses Newton's method: if there is an approximation, $y_{n}$ for $y$, then a better approximation $y_{n+1}$ can be calculated by taking $y_{n}-{\tfrac {f(y_{n})}{f'(y_{n})}}$, where $f'(y_{n})$ is the derivative of $f(y)$ at $y_{n}$. Applied to the equation ${\tfrac {1}{y^{2}}}-x=0$, Newton's method gives
    ${\begin{aligned}f(y)&={\frac {1}{y^{2}}}-x\\f'(y)&=-{\frac {2}{y^{3}}}\\y_{n+1}&=y_{n}-{\frac {f(y_{n})}{f'(y_{n})}}\\&=y_{n}+{\frac {y_{n}^{3}}{2}}\left({\frac {1}{y_{n}^{2}}}-x\right)\\&=y_{n}\left({\frac {3}{2}}-{\frac {x}{2}}y_{n}^{2}\right),\end{aligned}}$
which is written in the code as y = y * ( threehalfs - ( x2 * y * y ) );.
By repeating this step, using the output of the function ($y_{n+1}$) as the input of the next iteration, the algorithm causes $y$ to converge to the inverse square root. For the purposes of the Quake III engine, only one iteration was used. A second iteration remained in the code but was commented out.

### Accuracy

As noted above, the approximation is very accurate. The single graph on the right plots the error of the function (that is, the error of the approximation after it has been improved by running one iteration of Newton's method), for inputs starting at 0.01, where the standard library gives 10.0 as a result, and InvSqrt gives 9.982522, making the relative difference 0.0017478, or 0.175% of the true value, 10. The absolute error only drops from then on, and the relative error stays within the same bounds across all orders of magnitude.

## Subsequent improvements
### Magic number

It is not known precisely how the exact value for the magic number was determined. Chris Lomont developed a function to minimize approximation error by choosing the magic number $R$ over a range. He first computed the optimal constant for the linear approximation step as 0x5F37642F, close to 0x5F3759DF, but this new constant gave slightly less accuracy after one iteration of Newton's method. Lomont then searched for a constant optimal even after one and two Newton iterations and found 0x5F375A86, which is more accurate than the original at every iteration stage. He concluded by asking whether the exact value of the original constant was chosen through derivation or trial and error. Lomont said that the magic number for 64-bit IEEE754 size type double is 0x5FE6EC85E7DE30DA, but it was later shown by Matthew Robertson to be exactly 0x5FE6EB50C7B537A9.
Jan Kadlec reduced the relative error by a further factor of 2.7 by adjusting the constants in the single Newton's method iteration as well, arriving after an exhaustive search at
A complete mathematical analysis for determining the magic number is now available for single-precision floating-point numbers.

### Zero finding

Intermediate to the use of one vs. two iterations of Newton's method in terms of speed and accuracy is a single iteration of Halley's method. In this case, Halley's method is equivalent to applying Newton's method with the starting formula $f(y)={\frac {1}{y^{1/2}}}-xy^{3/2}=0$. The update step is then
    $y_{n+1}=y_{n}-{\frac {f(y_{n})}{f'(y_{n})}}=y_{n}\left({\frac {3+xy_{n}^{2}}{1+3xy_{n}^{2}}}\right),$
where the implementation should calculate $xy_{n}^{2}$ only once, via a temporary variable.

### Obsolescence

Subsequent additions by hardware manufacturers have made this algorithm redundant for the most part. For example, on x86, Intel introduced the SSE instruction rsqrtss in 1999. In a 2009 benchmark on the Intel Core 2, this instruction took 0.85ns per float compared to 3.54ns for the fast inverse square root algorithm, and had less error.
Some low-cost embedded systems do not have specialized square root instructions. However, manufacturers of these systems usually provide trigonometric and other math libraries, based on algorithms such as CORDIC.