Jay Taylor's notes

back to listing index

0x5f3759df | Hummus and Magnets

[web search]
Original source (h14s.p5r.org)
Tags: programming math fast-inverse-square-root h14s.p5r.org
Clipped on: 2014-11-12

0x5f3759df

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:

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 fuck?
  x = *(float*)&i;
  x = x*(1.5f-(xhalf*x*x));
  return x;
}

What this code does is calculate, quickly, a good approximation for

Image (Asset 1/46) alt=