So what do you think this code does?

Math(s) symbols
Image by Chuk Yong from Pixabay

Here’s a little C function. It’s not exactly intuitive what it does and I’ve renamed it to prevent giving it away.

  float mystery( float number )
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;                       
    i  = 0x5f3759df - ( i >> 1 );               
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );   
    return y;

If it helps, this line is really the heart of it.

    i  = 0x5f3759df - ( i >> 1 );  

Mystified? Well it’s a fast inverse square root. No one really knows who wrote it though John Carnack of Quake and Doom fame popularised it. There’s an interesting discussion about the author but no one really knows.

There’s less need for this type of thing nowadays because of all the fast silicon but back 20-25 years ago when graphics processors were in their very infancy, it was a highly useful optimization. Mind you , you’d need to know assembly language inside out to come up with stuff like this.