fast square root doom in csharp

One way to calculate the square root of a number in C# is to use the built-in Math.Sqrt method. However, this method can be slow for large numbers or when performance is critical. If you need to compute the square root of a number quickly, you can use an optimized algorithm that bypasses the built-in method.

One such algorithm is the Fast Inverse Square Root algorithm, which was originally developed for the game Quake III. This algorithm uses bitwise operations and floating-point arithmetic to approximate the inverse square root of a number, which can then be used to calculate the square root.

Here is an implementation of the Fast Inverse Square Root algorithm in C#:

main.cs
public static float FastSqrt(float num)
{
    const float threehalfs = 1.5f;

    unsafe
    {
        float x2 = num * 0.5f;
        float y = num;
        uint i = *(uint*)&y;

        i = 0x5f3759df - (i >> 1);
        y = *(float*)&i;
        y = y * (threehalfs - (x2 * y * y));

        return 1.0f / y;
    }
}
318 chars
18 lines

This implementation uses C#'s unsafe keyword to access the memory address of the float value. This allows us to perform bitwise operations on the value without having to convert to integer values.

Note that this algorithm produces an approximation of the square root, but the error is generally small enough to be negligible.

gistlibby LogSnag