A beautiful function
Una dintre diferentele intre un programator bun si unul slab este demonstrata de urmatoarea functie :
float InvSqrt(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating value
i = 0×5f3759df - (i>>1); // gives initial guess y0
x = *(float*)&i; // convert bits back to float
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
return x;
}
echivalent cu 1/Math.sqrt(x) …sau nu.
O explicatie mai simpla aici si una complexa aici.
Nu uitati totusi de urmatorul citat :
“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” (Knuth, Donald.)