Fast inverse square root

Fast inverse square root, sometimes referred to as Template:Mono or by the hexadecimal constant Template:Mono, is an algorithm that estimates , the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number 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,[1] though it remains an interesting historical example.[2]
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 Template:Mono, which is a floating-point representation of an approximation of .[3] 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.[4] In the late 1980s, Cleve Moler at Ardent Computer learned about this technique[5] 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.[6][7]
Jim Blinn demonstrated a simple approximation of the inverse square root in a 1997 column for IEEE Computer Graphics and Applications.Template:Sfn Reverse engineering of other contemporary 3D video games uncovered a variation of the algorithm in Activision's 1997 Interstate '76.[8]
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.[6] A discussion of the code appeared on the Chinese developer forum CSDN in 2000,[9] and Usenet and the gamedev.net forum spread the code widely in 2002 and 2003.Template:Sfn Speculation arose as to who wrote the algorithm and how the constant was derived; some guessed John Carmack.[7] Quake IIITemplate:'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.[6]
In 2007 the algorithm was implemented in some dedicated hardware vertex shaders using field-programmable gate arrays (FPGA).[10]Template:Sfn
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.Template:Sfn 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.[7] 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 would be a vector . Then,
is the Euclidean norm of the vector, and the normalized (unit) vector is
where the fraction term is the inverse square root of .
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:[11]
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 , 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.Template:Sfn 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.Template:Sfn 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.Template:Sfn
The advantages in speed offered by the fast inverse square root trick came from treating the 32-bit floating-point word[note 1] as an integer, then subtracting it from a "magic" constant, Template:Mono.[7]Template:SfnTemplate:SfnTemplate:Sfn 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.Template:R
Worked example
As an example, the number can be used to calculate . 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 , which has an error of about 3.4%. After one iteration of Newton's method, the final result is , 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.
# 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;
}
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:
import std;
constexpr std::float32_t Q_rsqrt(std::float32_t number) noexcept
{
const auto y = std::bit_cast<std::float32_t>(
0x5f3759df - (std::bit_cast<std::uint32_t>(number) >> 1));
return y * (1.5f32 - (number * 0.5f32 * y * y));
}
Algorithm
The algorithm computes by performing the following steps:
- Alias the argument to an integer as a way to compute an approximation of the binary logarithm
- Use this approximation to compute an approximation of
- 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 as a single precision float, the first step is to write as a normalized binary number:Template:Sfn
where the exponent is an integer, and 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:
where means , so . From this form, three unsigned integers are computed:Template:Sfn
- , the "sign bit", is if is positive and negative or zero (1 bit)
- is the "biased exponent", where is the "exponent bias"[note 2] (8 bits)
- , where [note 3] (23 bits)
Thus: and .
These fields are then packed, left to right, into a 32-bit container.Template:Sfn
As an example, consider again the number . Normalizing yields:
and thus, the three unsigned integer fields are:
these fields are packed as shown in the figure below:

The number is represented in binary as:
Also, since this algorithm works on real numbers, is only defined for . The code thus assumes and .
The number, given to calculate the square root, could be rewritten as:
Aliasing to an integer as an approximate logarithm
If were to be calculated without a computer or a calculator, a table of logarithms would be useful, together with the identity , which is valid for every base . 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 is a positive normal number:
then
and since , the logarithm on the right-hand side can be approximated byTemplate:Sfn
where is a free parameter used to tune the approximation. For example, yields exact results at both ends of the interval, while 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
Interpreting the floating-point bit-pattern of as an integer yields[note 4]
It then appears that is a scaled and shifted piecewise-linear approximation of , as illustrated in the figure on the right. In other words, is approximated by
First approximation of the result
The calculation of is based on the identity
Using the approximation of the logarithm above, applied to both and , the above equation gives:
Thus, an approximation of is:
which is written in the code as
i = 0x5f3759df - ( i >> 1 );
The first term above is the magic number
from which it can be inferred that . The second term, , is calculated by shifting the bits of one position to the right.Template:Sfn
Newton's method
Template:Main Template:Multiple image The number is a solution of the equation . 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, for , then a better approximation can be calculated by taking , where is the derivative of at .Template:Sfn Applied to the equation , Newton's method gives
which is written in the code as y = y * ( threehalfs - ( x2 * y * y ) );.
By repeating this step, using the output of the function () as the input of the next iteration, the algorithm causes to converge to the inverse square root.Template:Sfn For the purposes of the Quake III engine, only one iteration was used. A second iteration remained in the code but was commented out.Template:Sfn
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 over a range. He first computed the optimal constant for the linear approximation step as Template:Mono, close to Template:Mono, but this new constant gave slightly less accuracy after one iteration of Newton's method.Template:Sfn Lomont then searched for a constant optimal even after one and two Newton iterations and found Template:Mono, which is more accurate than the original at every iteration stage.Template:Sfn He concluded by asking whether the exact value of the original constant was chosen through derivation or trial and error.Template:Sfn Lomont said that the magic number for 64-bit IEEE754 size type double is Template:Mono, but it was later shown by Matthew Robertson to be exactly Template:Mono.[12]
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,[13] 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.Template:Sfn[14]
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 . The update step is then
where the implementation should calculate 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.[1]
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.
See also
Notes
References
Bibliography
- Template:Cite journal
- Template:Cite book
- Template:Cite book
- Template:Cite journal
- Template:Cite book
- Template:Cite book
- Template:Cite web
- Template:Cite web
- Template:Cite conference Template:Open access
- Template:Cite web
- Template:Cite web
- Template:Cite journal
Further reading
External links
- 0x5f3759df, further investigations into accuracy and generalizability of the algorithm by Christian Plesner Hansen
- Origin of Quake3's Fast InvSqrt()
- Quake III Arena source code (archived in Software Heritage)
- Implementation of InvSqrt in DESMOS
- "Fast Inverse Square Root β A Quake III Algorithm" (YouTube)
Template:Quake Template:Id Software
- β 1.0 1.1 Cite error: Invalid
<ref>tag; no text was provided for refs namedruskin - β Cite error: Invalid
<ref>tag; no text was provided for refs namedz88dk - β Cite error: Invalid
<ref>tag; no text was provided for refs namedmrob - β Cite error: Invalid
<ref>tag; no text was provided for refs namedfdlibm - β Cite error: Invalid
<ref>tag; no text was provided for refs namedMolerResp - β 6.0 6.1 6.2 Cite error: Invalid
<ref>tag; no text was provided for refs namedBeyond3Dp2 - β 7.0 7.1 7.2 7.3 Cite error: Invalid
<ref>tag; no text was provided for refs namedBeyond3D - β Template:Cite web
- β Cite error: Invalid
<ref>tag; no text was provided for refs namedcsdn - β Template:Cite book
- β Cite error: Invalid
<ref>tag; no text was provided for refs namedquakesrc - β Cite error: Invalid
<ref>tag; no text was provided for refs namedrobertson - β Template:Cite web
- β Template:Cite journal
Cite error: <ref> tags exist for a group named "note", but no corresponding <references group="note"/> tag was found