# Fast inverse square root Lighting and reflection calculations (shown here in the first-person shooter OpenArena) use the fast inverse square root code to compute angles of incidence and reflection.

Fast inverse square root, sometimes referred to as Fast InvSqrt() or by the hexadecimal constant 0x5F3759DF, is an algorithm that estimates 1x, the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number x in IEEE 754 floating-point format. This operation is used in digital signal processing to normalize a vector, i.e., scale it to length 1. For example, computer graphics programs use inverse square roots to compute angles of incidence and reflection for lighting and shading. The algorithm is best known for its implementation in 1999 in the source code of Quake III Arena, a first-person shooter video game that made heavy use of 3D graphics. The algorithm only started appearing on public forums such as Usenet in 2002 or 2003.[note 1] At the time, it was generally computationally expensive to compute the reciprocal of a floating-point number, especially on a large scale; the fast inverse square root bypassed this step.

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 2127. 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.

The algorithm was originally attributed to John Carmack, but an investigation showed that the code had deeper roots in both the hardware and software side of computer graphics. Adjustments and alterations passed through both Silicon Graphics and 3dfx Interactive, with Gary Tarolli's implementation for the SGI Indigo as the earliest known use. It is not known how the constant was originally derived, though investigation has shed some light on possible methods.

With subsequent hardware advancements, especially the x86 SSE instruction rsqrtss, this method is not generally applicable to modern computing, though it remains an interesting example both historically and for more limited machines.

## Motivation Surface normals are used extensively in lighting and shading calculations, requiring the calculation of norms for vectors. A field of vectors normal to a surface is shown here. A two-dimensional example of using the normal C to find the angle of reflection from the angle of incidence; in this case, on light reflecting from a curved mirror. The fast inverse square root is used to generalize this calculation to three-dimensional space.

The inverse square root of a floating point number is used in calculating a normalized vector. Programs can use normalized vectors to determine angles of incidence and reflection. 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 behind the speed of integer processing. This was troublesome for 3D graphics programs before the advent of specialized hardware to handle transform and lighting.

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 v would be a vector (v1, v2, v3).

$\|{\boldsymbol {v}}\|={\sqrt {v_{1}^{2}+v_{2}^{2}+v_{3}^{2}}}$ is the Euclidean norm of the vector.

${\boldsymbol {\hat {v}}}={\frac {\boldsymbol {v}}{\left\|{\boldsymbol {v}}\right\|}}$ is the normalized (unit) vector, using ||v||2 to represent v2
1
+ v2
2
+ v2
3
.

${\boldsymbol {\hat {v}}}={\frac {\boldsymbol {v}}{\sqrt {\left\|{\boldsymbol {v}}\right\|^{2}}}}$ which relates the unit vector to the inverse square root of the distance components. The inverse square root can be used to compute because this equation is equivalent to

${\boldsymbol {\hat {v}}}={\boldsymbol {v}}\,{\frac {1}{\sqrt {\left\|{\boldsymbol {v}}\right\|^{2}}}}$ where the fraction term is the inverse square root of ||v||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. Quake III Arena, a first-person shooter video game, used the fast inverse square root algorithm to accelerate graphics computation, but the algorithm has since been implemented in some dedicated hardware vertex shaders using field-programmable gate arrays (FPGA).

## Overview of the code

The following code is the fast inverse square root implementation from Quake III Arena, stripped of C preprocessor directives, but including the exact original comment text:

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


At the time, the general method to compute the inverse square root was to calculate an approximation for 1x, 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 kludge came from treating the longword[note 2] containing the floating point number as an integer then subtracting it from a specific constant, 0x5F3759DF. The purpose of the constant is not immediately clear to someone viewing the code, so, like other such constants found in code, it is often called a magic number. This integer subtraction and bit shift results in a longword which when treated as a floating point number is a rough approximation for the inverse square root of the input 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.

According to the C standard, reinterpreting a floating point value as an integer by dereferencing a casted pointer to it is considered undefined behavior.

float Q_rsqrt( float number )
{
const float x2 = number * 0.5F;
const float threehalfs = 1.5F;

union {
float f;
uint32_t i;
} conv = {number}; // member 'f' set to value of 'number'.
conv.i  = 0x5f3759df - ( conv.i >> 1 );
conv.f  *= ( threehalfs - ( x2 * conv.f * conv.f ) );
return conv.f;
}


### A worked example

As an example, the number x = 0.15625 can be used to calculate 1x ≈ 2.52982. The first steps of the algorithm are illustrated below:

0011_1110_0010_0000_0000_0000_0000_0000  Bit pattern of both x and i
0001_1111_0001_0000_0000_0000_0000_0000  Shift right one position: (i >> 1)
0101_1111_0011_0111_0101_1001_1101_1111  The magic number 0x5F3759DF
0100_0000_0010_0111_0101_1001_1101_1111  The result of 0x5F3759DF - (i >> 1)


Interpreting as IEEE 32-bit representation:

0_01111100_01000000000000000000000  1.25 × 2−3
0_00111110_00100000000000000000000  1.125 × 2−65
0_10111110_01101110101100111011111  1.432430... × 263
0_10000000_01001110101100111011111  1.307430... × 21


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 single iteration of Newton's method, the final result is y = 2.52549, an error of only 0.17%.

## Algorithm

The algorithm computes 1x by performing the following steps:

1. Alias the argument x to an integer as a way to compute an approximation of log2(x)
2. Use this approximation to compute an approximation of log2(​1x)= −1/2 log2(x)
3. Alias back to a float, as a way to compute an approximation of the base-2 exponential
4. Refine the approximation using a single iteration of the 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. In order 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}}\\&=\pm 2^{e_{x}}(1+m_{x})\end{aligned}} where the exponent ex is an integer, mx ∈ [0, 1), and 1.b1b2b3... is the binary representation of the "significand" (1 + mx). Since the single bit before the point in the significand is always 1, it need not be stored. From this form, three unsigned integers are computed:

• Sx, the "sign bit", is 0 if x > 0, and 1 if x < 0 (1 bit)
• Ex = ex + B is the "biased exponent", where B = 127 is the "exponent bias"[note 3] (8 bits)
• Mx = mx × L, where L = 223[note 4] (23 bits)

These fields are then packed, left to right, into a 32-bit container.

As an example, consider again the number x = 0.15625 = 0.001012. Normalizing x yields:

x = +2−3(1 + 0.25)

and thus, the three unsigned integer fields are:

• S = 0
• E = −3 + 127 = 124 = 011111002
• M = 0.25 × 223 = 2097152 = 010000000000000000000002

these fields are packed as shown in the figure below:

### Aliasing to an integer as an approximate logarithm

If 1x was to be calculated without a computer or a calculator, a table of logarithms would be useful, together with the identity logb(​1x) = −1/2 logb(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 mx ∈ [0, 1), the logarithm on the right hand side can be approximated by

$\log _{2}(1+m_{x})\approx m_{x}+\sigma$ where σ is a free parameter used to tune the approximation. For example, σ = 0 yields exact results at both ends of the interval, while σ ≈ 0.0430357 yields the optimal approximation (the best in the sense of the uniform norm of the error). The integer aliased to a floating point number (in blue), compared to a scaled and shifted logarithm (in gray).

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 Ix yields[note 5]

{\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 Ix is a scaled and shifted piecewise-linear approximation of log2(x), as illustrated in the figure on the right. In other words, log2(x) is approximated by

$\log _{2}(x)\approx {\frac {I_{x}}{L}}-(B-\sigma ).$ ### First approximation of the result

The calculation of y = ​1x 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 Iy 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 )={\text{0x5F3759DF}}$ from which it can be inferred that σ ≈ 0.0450466. The second term, 1/2Ix, is calculated by shifting the bits of Ix one position to the right.

### Newton's method Relative error between fast inverse square root carrying out 3 iterations of Newton's root-finding method, and direct calculation. Note that double precision is adopted. Smallest representable difference between two double precision numbers is reached after carrying out 4 iterations.

With y as the inverse square root, f (y) = 1/y2x = 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, yn for y, then a better approximation yn+1 can be calculated by taking ynf (yn)/f ′(yn), where f ′(yn) is the derivative of f (y) at yn. For the above f (y),

$y_{n+1}={\frac {y_{n}\left(3-xy_{n}^{2}\right)}{2}}$ where f (y) = 1/y2x and f ′(y) = −2/y3.

Treating y as a floating-point number, y = y*(threehalfs - x2*y*y); is equivalent to

$y_{n+1}=y_{n}\left({\frac {3}{2}}-{\frac {x}{2}}y_{n}^{2}\right)={\frac {y_{n}\left(3-xy_{n}^{2}\right)}{2}}.$ By repeating this step, using the output of the function (yn+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 A graph showing the difference between the heuristic fast inverse square root and the direct inversion of square root supplied by libstdc.[citation needed] (Note the log scale on both axes.)

As noted above, the approximation is surprisingly accurate. The 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, while InvSqrt() gives 9.982522, making the difference 0.017479, or 0.175% of the true value, 10. The absolute error only drops from then on, while the relative error stays within the same bounds across all orders of magnitude.

## History and investigation

The source code for Quake III was not released until QuakeCon 2005, but copies of the fast inverse square root code appeared on Usenet and other forums as early as 2002 or 2003. Initial speculation pointed to John Carmack as the probable author of the code, but he demurred and suggested it was written by Terje Mathisen, an accomplished assembly programmer who had previously helped id Software with Quake optimization. Mathisen had written an implementation of a similar bit of code in the late 1990s, but the original authors proved to be much further back in the history of 3D computer graphics with Gary Tarolli's implementation for the SGI Indigo as a possible earliest known use. Rys Sommefeldt concluded that the original algorithm was devised by Greg Walsh at Ardent Computer in consultation with Cleve Moler, the creator of MATLAB. Cleve Moler learned about this trick from code written by William Kahan and K.C. Ng at Berkeley around 1986 Jim Blinn also demonstrated a simple approximation of the inverse square root in a 1997 column for IEEE Computer Graphics and Applications. Paul Kinney implemented a fast method for the FPS T Series computer around 1986. The system included vector floating-point hardware which was not rich in integer operations. The floating-point values were floated to allow manipulation to create the initial approximation.

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.

A complete mathematical analysis for determining the magic number is now available for single-precision floating-point numbers.