fast square root in csharp

To compute the square root of a number in c#, we can use the Math.Sqrt() method that is part of the standard library. However, this method may not be the fastest solution in all cases, especially when we need to compute the square root of many numbers.

A faster alternative is the Babylonian method or Heron's method. This algorithm starts with an initial estimate of the square root and iteratively refines it until it converges to the accurate value.

Here is an implementation of the Babylonian method in c#:

main.cs
public static double FastSqrt(double num)
{
    double guess = num / 2; // initial guess
    double prevGuess;

    do
    {
        prevGuess = guess;
        guess = (guess + num / guess) / 2; // update guess
    } while (prevGuess - guess > double.Epsilon * guess); // check convergence

    return guess;
}
311 chars
14 lines

To use this method, we just need to call FastSqrt() with the number we want to sqrt:

main.cs
var result = FastSqrt(25.0);
Console.WriteLine(result); // Output: 5.0
71 chars
3 lines

Note that this method may have some accuracy issues due to floating-point arithmetic, but it is generally faster than Math.Sqrt() for large numbers or when we need to compute the square root of many numbers.

gistlibby LogSnag