Inverse square root hack

ViN86

Well-known member
This subforum seems pretty dead, so I will post some stories/blogs/posts I find online occasionally here.

I came across this post on r/programming. It's a nice hack to get a very fast approximation for the inverse square root function (e.g. 1/sqrt(x)).

http://h14s.p5r.org/2012/09/0x5f3759df.html

0x5f3759df
Posted on September 15, 2012 | 68 Comments
This post is about the magic constant 0x5f3759df and an extremely neat hack, fast inverse square root, which is where the constant comes from.

Meet the inverse square root hack:

Code:
float FastInvSqrt(float x) {
  float xhalf = 0.5f * x;
  int i = *(int*)&x;         // evil floating point bit level hacking
  i = 0x5f3759df - (i >> 1);  // what the ****?
  x = *(float*)&i;
  x = x*(1.5f-(xhalf*x*x));
  return x;
}
What this code does is calculate, quickly, a good approximation for

\frac{1}{\sqrt{x}}

It’s a fairly well-known function these days and first became so when it appeared in the source of Quake III Arena in 2005. It was originally attributed to John Carmack but turned out to have a long history before Quake going back through SGI and 3dfx to Ardent Computer in the mid 80s to the original author Greg Walsh. The concrete code above is an adapted version of the Quake code (that’s where the comments are from).

This post has a bit of fun with this hack. It describes how it works, how to generalize it to any power between -1 and 1, and sheds some new light on the math involved.
 
Back
Top