steve_bank
Diabetic retinopathy and poor eyesight. Typos ...
I get the impression that a lot of the most interesting programming happens on embedded systems, where resources are highly constrained and there is a big incentive to make programs as lean and efficient as possible.
I'm reminded of John Carmack's fast inverse square root function. It's a pretty cool example of using various tricks to create a function that minimises execution time by calculating an approximate result, and does so with a couple of nifty tricks.
C: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; }
I appreciate creative problem solving.
It took three iterations of the last line to match the compiler library sqrt function, so I'd call it a successive approximation algorithm.
There may be portability problems. With the way I have my compiler options set it compiles wit warnings of the de-referencing. It may not compile on a struct rule compiler like MS C++.
The function works with 32 bit ints and 32 bit floats. Float and double are both 32 bit, but the function fails with doubles. It probably has something to do with the pointers. Possible potability problem.
I haven't reduced it to an equation. The right shift is a divide by 2 and I haven't figured out where the hex constant comes from. Something to chew on for a while.