Fast Inverse Square Root
#include <cstdint>
float FastInverseSqrt(float x) {
float xhalf = 0.5f * x;
int32_t i = (int32_t)&x; // reinterpret bits of x as an integer
i = 0x5f3759df - (i >> 1); // initial guess for the inverse square root
x = (float)&i; // convert bits back to float
x = x (1.5f - xhalf x * x); // Newton-Raphson iteration to improve accuracy
return x;
}
Explanation:
float xhalf = 0.5f * x;
: Compute half of the input value.int32_t i = (int32_t)&x;
: Interpret the bits of the floating-point numberx
as an integer.i = 0x5f3759df - (i >> 1);
: Apply a magic number and some bit manipulation to make an initial guess for the inverse square root using integer operations.x = (float)&i;
: Convert the bits back to a floating-point number.x = x (1.5f - xhalf x * x);
: Perform one iteration of the Newton-Raphson method to refine the estimate of the inverse square root.Return the computed value
x
.