Ok, by far, I guess many people know the famous fast inverse square root (see more on Writing your own square root function and 0x5f3759df)
Here is the code
float FastInvSqrt(float x) {
float xhalf = 0.5f * x;
int i = *(int*)&x; // evil floating point bit level hacking
i = 0x5f3759df - (i >> 1); // what the fuck?
x = *(float*)&i;
x = x*(1.5f-(xhalf*x*x)); // one Newton Method iteration
return x;
}
Ok, i do NOT need to know more how magic 0x5f3759df
is.
What I don't understand is why x*(1.5f-(xhalf*x*x))
is a Newton Method
iteration?
I tried analyse but just can't get it.
So let's assume r is the real number and x is the inverse sqrt of r.
1 / (x^2) = r
, then f(x) = r*(x^2)-1
and f'(x) = 2 * r * x
So one iteration should be x1 = x - f(x)/f'(x) = x / 2 + 1 / (2 * r * x)
, right?
How comes x * (1.5 - ((r / 2) * x * x))
? (note I replaced xhalf
with r / 2
here)
Edit
Ok f(x) = x^2 - 1/r
is another form, let me calculate
f(x) = x^2 - 1 / r
f'(x) = 2 * x
So x1 = x - (f(x)/f'(x)) = x - (x^2 -(1 / r))/(2*x) = x / 2 + 1 / (2 * r * x)
, still it is quite different from the formula used in the code, right?