Is it possible to write Quake's fast InvSqrt() function in C#?
<p>This is just to satisfy my own curiosity.</p>

<p>Is there an implementation of this:</p>

<pre><code>float InvSqrt (float x)
{
   float xhalf = 0.5f*x;
   int i = *(int*)&amp;x;
   i = 0x5f3759df - (i&gt;&gt;1);
   x = *(float*)&amp;i;
   x = x*(1.5f - xhalf*x*x);
   return x;
}
</code></pre>

<p>in C#?  If it exists, post the code.  </p>

<p>I guess I should have mentioned I was looking for a "safe" implementation...  Either way, the BitConverter code solves the problem.  The union idea is interesting.  I'll test it and post my results.</p>

<p>Edit:
As expected, the unsafe method is the quickest, followed by using a union (inside the function), followed by the BitConverter.  The functions were executed 10000000 times, and the I used the System.Diagnostics.Stopwatch class for timing.  The results of the calculations are show in brackets.</p>

<pre><code>Input: 79.67
BitConverter Method: 00:00:01.2809018 (0.1120187)
Union Method: 00:00:00.6838758 (0.1120187)
Unsafe Method: 00:00:00.3376401 (0.1120187)
</code></pre>

<p>For completeness, I tested the built-in Math.Pow method, and the "naive" method (1/Sqrt(x)).</p>

<pre><code>Math.Pow(x, -0.5): 00:00:01.7133228 (0.112034710535584)
1 / Math.Sqrt(x): 00:00:00.3757084 (0.1120347)
</code></pre>

<p>The difference between 1 / Math.Sqrt() is so small that I don't think one needs to resort to the Unsafe Fast InvSqrt() method in C# (or any other unsafe method).  Unless one <em>really</em> needs to squeeze out that last bit of juice from the CPU...  1/Math.Sqrt() is also much more accurate.</p>
