Skip to content

Comment on Ask HN: What's the most elegant piece of code you've seen?

Comments

I love the story of the fast inverse square root. A bizzare piece of code from quake 3 shows up on usenet with a magic constant that calculates the inverse square root faster than table lookups and approximately four times faster than regular floating point division. Inverse square roots are used to compute angles of incidence and reflection for lighting and shading in computer graphics. Author unknown but was once thought as of Carmack.

https://en.m.wikipedia.org/wiki/Fast_inverse_square_root

I would say that the actual source code there is extremely ugly. It may be an elegant solution, but there's no way I would want to crawl around in that repo:

    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;
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.