some guy i was tutoring in math showed me this. i found it veryyyyy interesting:
Code:
float InvSqrt(float x) {
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f-xhalf*x*x);
return x;
}
because he wanted to know where calculus was going, so i showed him a lot of the really interesting things Newton did. this was one for approximating roots.
i derived that for him, showed him how it works, and why its good. he then referred me to this code i posted already.
now even if your not a c programmer (i also am not a c programmer, just program in a couple languages as a hobby) you should have a basic idea of what its doing just by looking at it. its taking a float and casting the pointer to it, to be an int, so even through its a float it is now referred to as an int, allowing bit shifting. after the shifted int it is turned back into a float, it has guessed an initial guess point for newtons method and done the first step.
a float is a 32bit number that has a decimal in it. it works like scientific notation.
the bit shifting moves the least significant bit from the expoent and makes it the most significant bit in the base, while the bass looses its least significant bit, dividing it by 2 and subtracting 1 if it is off. its almost moving the sign bit into the exponent, but thats 0 for positive anyways.
this still does not explain how it works, and how it works so well.
i would be interesting in any insight anybody has about how this really works.