Here is a algorithm I have come up with to calculate the square root, currently when testing it with a loop n times and stopwatch it's about 20-100x slower then C# Math.Sqrt()
;
Is there any way to improve the performance of this function or is the performance as good as it gonna get with this specific algorithm?
My C# square root algorithm:
static class MyMath
{
public static double Sqrt(double _d)
{
double x = 0;
double y = 2;
double z = 1;
double w = _d;
double h = 1;
double t = 0;
double px = 0;
int itr = 0;
while (true)
{
w = (w / y);
h *= y;
if (h > w)
{
t = w;
w = h;
h = t;
z *= 0.5;
y = (1 + z);
}
x = ((w + h) * 0.5);
if (itr >= 100 || w == h || px == x)
{
return (x);
}
px = x;
itr++;
}
}
}
How I test the performance:
using System.Diagnostics;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000; i++)
{
MyMath.Sqrt(2);
}
sw.Stop();
Debug.Print(sw.ElapsedTicks.ToString());
EDIT3: Slightly improved version:
static class MyMath
{
public static double Sqrt(double _d)
{
double x = 0;
double y = 2;
double z = 1;
double w = _d;
double h = 1;
double t = 0;
double px = 1;
while (true)
{
if (x == px)
{
return ((w + h) * 0.5);
}
if (w < h)
{
t = w;
w = h;
h = t;
z *= 0.25;
y = (z + 1);
px = x;
}
w /= y;
h *= y;
x = (w + h);
}
}
}
EDIT3: Updated Slightly improved version2 + changed benchmark method2: (Running in Release Mode)
Stopwatch sw = new Stopwatch();
int n = 100000;
double[] squareArr = new double[n];
Random rng = new Random(1234);
for (int i = 0; i < n; i++)
{
squareArr[i] = rng.Next(1, 100000);
}
sw.Start();
for (int i = 0; i < n; i++)
{
squareArr[i] = MyMath.Sqrt(squareArr[i]) ;
}
sw.Stop();
debugBox.AppendText("AverageTime: " + (sw.ElapsedTicks / (double)n).ToString());
Currently according to my test the default Math.Sqrt() ~0.086 Ticks and mySqrt() ~4.8 Ticks.
EDIT 4:(Fixed bug: moved px = x in if statement)