# Fast inverse square root

Lighting and reflection calculations, as in the video game 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 ${\displaystyle {\frac {1}{\sqrt {x}}}}$, the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number ${\displaystyle x}$ in IEEE 754 floating-point format. This operation is used in digital signal processing to normalize a vector, such as scaling it to length 1. For example, computer graphics programs use inverse square roots to compute angles of incidence and reflection for lighting and shading. Predated by similar video game algorithms, this one is best known for its implementation in 1999 in Quake III Arena, a first-person shooter video game heavily based on 3D graphics. The algorithm only started appearing on public forums between 2002 and 2003.[note 1] 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 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 (in decimal notation: 1,597,463,007), which is a floating-point representation of an approximation of ${\displaystyle {\sqrt {2^{127}}}}$.[2] 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 often misattributed to John Carmack, but in fact the code is based on an unpublished paper by William Kahan and K.C. Ng circulated in May 1986. The original constant was produced from a collaboration between Cleve Moler and Gregory Walsh, while they worked for Ardent Computing in the late 1980s.

With subsequent hardware advancements, especially the x86 SSE instruction rsqrtss, this method is not generally applicable to general purpose computing,[3] though it remains an interesting example both historically[4] and for more limited machines, such as low-cost embedded systems. However, more manufacturers of embedded systems are including trigonometric and other math accelerators such as CORDIC, avoiding the need for such algorithms.

## 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 ${\displaystyle 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.[5] 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 the speed of integer processing.[6] 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 ${\displaystyle {\boldsymbol {v}}}$ would be a vector ${\displaystyle (v_{1},v_{2},v_{3})}$.

${\displaystyle \|{\boldsymbol {v}}\|={\sqrt {v_{1}^{2}+v_{2}^{2}+v_{3}^{2}}}}$

is the Euclidean norm of the vector.

${\displaystyle {\boldsymbol {\hat {v}}}={\frac {\boldsymbol {v}}{\left\|{\boldsymbol {v}}\right\|}}}$

is the normalized (unit) vector, using ${\displaystyle \|{\boldsymbol {v}}\|^{2}}$ to represent ${\displaystyle v_{1}^{2}+v_{2}^{2}+v_{3}^{2}}$.

${\displaystyle {\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 ${\displaystyle {\boldsymbol {\hat {v}}}}$ because this equation is equivalent to

${\displaystyle {\boldsymbol {\hat {v}}}={\boldsymbol {v}}\,{\frac {1}{\sqrt {\left\|{\boldsymbol {v}}\right\|^{2}}}}}$

where the fraction term is the inverse square root of ${\displaystyle \|{\boldsymbol {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.

## 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:[7]

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 ${\displaystyle {\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.[8] 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.[9] 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.[10]

The advantages in speed offered by the fast inverse square root trick came from treating the 32-bit floating-point word[note 2] as an integer, then subtracting it from a "magic" constant, 0x5F3759DF.[6][11][12][13] 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.[3][14]

### Worked example

As an example, the number ${\displaystyle x=0.15625}$ can be used to calculate ${\displaystyle {\frac {1}{\sqrt {x}}}\approx 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 ${\displaystyle y=2.61486}$, which has an error of about 3.4%. After one single iteration of Newton's method, the final result is ${\displaystyle 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 removing the pointer to it is considered unexpected behavior (undefined behavior). Another way would be to place the floating point value in an anonymous 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. However, type punning through a union is also undefined behavior in C++.

#include <stdint.h> // uint32_t

float Q_rsqrt(float number)
{
union {
float    f;
uint32_t i;
} conv = { .f = number };
conv.i  = 0x5f3759df - (conv.i >> 1);
conv.f *= 1.5F - (number * 0.5F * conv.f * conv.f);
return conv.f;
}


In C++ the usual 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:

#include <bit>
#include <limits>
#include <cstdint>

constexpr float Q_rsqrt(float number) noexcept
{
static_assert(std::numeric_limits<float>::is_iec559); // (enable only on IEEE 754)

float const y = std::bit_cast<float>(
0x5f3759df - (std::bit_cast<std::uint32_t>(number) >> 1));
return y * (1.5f - (number * 0.5f * y * y));
}


## Algorithm

The algorithm computes ${\displaystyle {\frac {1}{\sqrt {x}}}}$ by performing the following steps:

1. Alias the argument ${\displaystyle x}$ to an integer as a way to compute an approximation of the binary logarithm ${\displaystyle \log _{2}(x)}$
2. Use this approximation to compute an approximation of ${\displaystyle \log _{2}\left({\frac {1}{\sqrt {x}}}\right)=-{\frac {1}{2}}\log _{2}(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 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 ${\displaystyle x}$ as a single precision float, the first step is to write ${\displaystyle x}$ as a normalized binary number:[15]

{\displaystyle {\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 ${\displaystyle e_{x}}$ is an integer, ${\displaystyle m_{x}\in [0,1)}$, and ${\displaystyle 1.b_{1}b_{2}b_{3}\ldots }$ is the binary representation of the "significand" ${\displaystyle (1+m_{x})}$. 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:[16]

• ${\displaystyle S_{x}}$, the "sign bit", is ${\displaystyle 0}$ if ${\displaystyle x}$ is positive and ${\displaystyle 1}$ negative or zero (1 bit)
• ${\displaystyle E_{x}=e_{x}+B}$ is the "biased exponent", where ${\displaystyle B=127}$ is the "exponent bias"[note 3] (8 bits)
• ${\displaystyle M_{x}=m_{x}\times L}$, where ${\displaystyle L=2^{23}}$[note 4] (23 bits)

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

As an example, consider again the number ${\displaystyle x=0.15625=0.00101_{2}}$. Normalizing ${\displaystyle x}$ yields:

${\displaystyle x=+2^{-3}(1+0.25)}$

and thus, the three unsigned integer fields are:

• ${\displaystyle S=0}$
• ${\displaystyle E=-3+127=124=0111\ 1100_{2}}$
• ${\displaystyle 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:

### Aliasing to an integer as an approximate logarithm

If ${\displaystyle {\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 ${\displaystyle \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 ${\displaystyle 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 ${\displaystyle x}$ is a positive normal number:

${\displaystyle x=2^{e_{x}}(1+m_{x})}$

then

${\displaystyle \log _{2}(x)=e_{x}+\log _{2}(1+m_{x})}$

and since ${\displaystyle m_{x}\in [0,1)}$, the logarithm on the right-hand side can be approximated by[18]

${\displaystyle \log _{2}(1+m_{x})\approx m_{x}+\sigma }$

where ${\displaystyle \sigma }$ is a free parameter used to tune the approximation. For example, ${\displaystyle \sigma =0}$ yields exact results at both ends of the interval, while ${\displaystyle \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.

The integer aliased to a floating point number (in blue), compared to a scaled and shifted logarithm (in gray).

Thus there is the approximation

${\displaystyle \log _{2}(x)\approx e_{x}+m_{x}+\sigma .}$

Interpreting the floating-point bit-pattern of ${\displaystyle x}$ as an integer ${\displaystyle I_{x}}$ yields[note 5]

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

${\displaystyle \log _{2}(x)\approx {\frac {I_{x}}{L}}-(B-\sigma ).}$

### First approximation of the result

The calculation of ${\displaystyle y={\frac {1}{\sqrt {x}}}}$ is based on the identity

${\displaystyle \log _{2}(y)=-{\tfrac {1}{2}}\log _{2}(x)}$

Using the approximation of the logarithm above, applied to both ${\displaystyle x}$ and ${\displaystyle y}$, the above equation gives:

${\displaystyle {\frac {I_{y}}{L}}-(B-\sigma )\approx -{\frac {1}{2}}\left({\frac {I_{x}}{L}}-(B-\sigma )\right)}$

Thus, an approximation of ${\displaystyle I_{y}}$ is:

${\displaystyle 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

${\displaystyle {\tfrac {3}{2}}L(B-\sigma )={\mathtt {0x5F3759DF}}}$

from which it can be inferred that ${\displaystyle \sigma \approx 0.0450466}$. The second term, ${\displaystyle {\frac {1}{2}}I_{x}}$, is calculated by shifting the bits of ${\displaystyle I_{x}}$ one position to the right.[19]

### Newton's method

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

With ${\displaystyle y}$ as the inverse square root, ${\displaystyle f(y)={\frac {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, ${\displaystyle y_{n}}$ for ${\displaystyle y}$, then a better approximation ${\displaystyle y_{n+1}}$ can be calculated by taking ${\displaystyle y_{n}-{\frac {f(y_{n})}{f'(y_{n})}}}$, where ${\displaystyle f'(y_{n})}$ is the derivative of ${\displaystyle f(y)}$ at ${\displaystyle y_{n}}$.[20] For the above ${\displaystyle f(y)}$,

${\displaystyle y_{n+1}={\frac {y_{n}\left(3-xy_{n}^{2}\right)}{2}}}$

where ${\displaystyle f(y)={\frac {1}{y^{2}}}-x}$ and ${\displaystyle f'(y)=-{\frac {2}{y^{3}}}}$.

Treating ${\displaystyle y}$ as a floating-point number, y = y*(threehalfs - x/2*y*y); is equivalent to

${\displaystyle 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 (${\displaystyle y_{n+1}}$) as the input of the next iteration, the algorithm causes ${\displaystyle y}$ to converge to the inverse square root.[21] For the purposes of the Quake III engine, only one iteration was used. A second iteration remained in the code but was commented out.[13]

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

## 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.[22] In the late 1980s, Cleve Moler at Ardent Computer learned about this technique[23] 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.[24][6]

Jim Blinn demonstrated a simple approximation of the inverse square root in a 1997 column for IEEE Computer Graphics and Applications.[25] Reverse engineering of other contemporary 3D video games uncovered a variation of the algorithm in Activision's 1997 Interstate '76.[26]

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.[24] Copies of the fast inverse square root code appeared on Usenet and other forums as early as 2002 or 2003. Speculation arose as to who wrote the algorithm and how the constant was derived; some guessed John Carmack.[6] Quake III's full source code was released at QuakeCon 2005, but provided no answers. The authorship question was answered in 2006.[24]

In 2007 the algorithm was implemented in some dedicated hardware vertex shaders using field-programmable gate arrays (FPGA).[27]

## 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 ${\displaystyle 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.[28] 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.[28] He concluded by asking whether the exact value of the original constant was chosen through derivation or trial and error.[29] 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.[30]

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,[31] arriving after an exhaustive search at

	conv.i = 0x5F1FFFF9 - ( conv.i >> 1 );
conv.f *= 0.703952253f * ( 2.38924456f - x * conv.f * conv.f );
return conv.f;


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

### 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 ${\displaystyle f(y)={\frac {1}{y^{1/2}}}-xy^{3/2}=0}$. The update step is then

${\displaystyle 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 ${\displaystyle xy_{n}^{2}}$ only once, via a temporary variable.

## Notes

1. ^ A discussion is on the Chinese developer forum CSDN from 2000.[1]
2. ^ Use of the type long reduces the portability of this code on modern systems. For the code to execute properly, sizeof(long) must be 4 bytes, otherwise negative outputs may result. Under many modern 64-bit systems, sizeof(long) is 8 bytes. The more portable replacement is int32_t.
3. ^ ${\displaystyle E_{x}}$ should be in the range ${\displaystyle [1,254]}$ for ${\displaystyle x}$ to be representable as a normal number.
4. ^ The only real numbers that can be represented exactly as floating point are those for which ${\displaystyle M_{x}}$ is an integer. Other numbers can only be represented approximately by rounding them to the nearest exactly representable number.
5. ^ Since ${\displaystyle x}$ is positive, ${\displaystyle S_{x}=0}$.

## References

1. ^ "Discussion on CSDN". Archived from the original on 2015-07-02.
2. ^ Munafo, Robert. "Notable Properties of Specific Numbers". mrob.com. Archived from the original on 16 November 2018.
3. ^ a b Ruskin, Elan (2009-10-16). "Timing square root". Some Assembly Required. Archived from the original on 2021-02-08. Retrieved 2015-05-07.
4. ^
5. ^ Blinn 2003, p. 130.
6. ^ a b c d Sommefeldt, Rys (2006-11-29). "Origin of Quake3's Fast InvSqrt()". Beyond3D. Retrieved 2009-02-12.
7. ^ "quake3-1.32b/code/game/q_math.c". Quake III Arena. id Software. Archived from the original on 2020-08-02. Retrieved 2017-01-21.
8. ^ Eberly 2001, p. 504.
9. ^ Lomont 2003, p. 1.
10. ^
11. ^ Lomont 2003, p. 3.
12. ^ McEniry 2007, p. 2, 16.
13. ^ a b Eberly 2001, p. 2.
14. ^ Fog, Agner. "Lists of instruction latencies, throughputs and micro-operation breakdowns for Intel, AMD and VIA CPUs" (PDF). Retrieved 2017-09-08.
15. ^ Goldberg 1991, p. 7.
16. ^ Goldberg 1991, pp. 15–20.
17. ^ Goldberg 1991, p. 16.
18. ^ McEniry 2007, p. 3.
19. ^ Hennessey & Patterson 1998, p. 305.
20. ^ Hardy 1908, p. 323.
21. ^ McEniry 2007, p. 6.
22. ^
23. ^ Moler, Cleve. "Symplectic Spacewar". MATLAB Central - Cleve's Corner. MATLAB. Retrieved 2014-07-21.
24. ^ a b c Sommefeldt, Rys (2006-12-19). "Origin of Quake3's Fast InvSqrt() - Part Two". Beyond3D. Retrieved 2008-04-19.
25. ^ Blinn 1997, pp. 80–84.
26. ^ Peelar, Shane (1 June 2021). "Fast reciprocal square root... in 1997?!".
27. ^ Middendorf 2007, pp. 155–164.
28. ^ a b Lomont 2003, p. 10.
29. ^ Lomont 2003, pp. 10–11.
30. ^ Matthew Robertson (2012-04-24). "A Brief History of InvSqrt" (PDF). UNBSJ.
31. ^ Kadlec, Jan (2010). "Řrřlog::Improving the fast inverse square root" (personal blog). Retrieved 2020-12-14.
32. ^
33. ^ Muller, Jean-Michel (December 2020). "Elementary Functions and Approximate Computing". Proceedings of the IEEE. 108 (12): 2146. doi:10.1109/JPROC.2020.2991885. ISSN 0018-9219.