In quakeiiiSource codeThere is a function for finding inverse square root (that is, 1/SQRT (x,
Implemented by CarmackAlgorithmSome CPUs are 4 times faster than normal (float) (1.0/SQRT (x! (SQRT (x) in the above expression is still calculated by directly calling the fsqrt command !!!)
Carmack'sCodeAs follows:
Float q_rsqrt (float number)
{
Long I;
Float X2, Y;
Const float threehalfs = 1.5f;
X2 = Number * 0.5f;
Y = number;
I = * (long *) & Y; // edevil floating point bit level hacking
I = 0x5f3759df-(I> 1); // What is the fuck?
Y = * (float *) & I;
Y = y * (threehalfs-(X2 * y); // 1st Iteration
// Y = y * (threehalfs-(X2 * y); // 2nd iteration, this can be removed
# Ifndef q3_vm
# Ifdef _ Linux __
Assert (! Isnan (y); // bk010122-FPE?
# Endif
# Endif
Return y;
}
It is actually an iteration of the Newton method, but Carmack uses a mysterious constant, 0x5f3759df. The result is obtained after only one iteration.
Chris lomont from Purdue University wrote a paper titled paper.
Genius is a genius, but Carmack is a high school graduate.