patterncsharpMinor
Square root function
Viewed 0 times
functionrootsquare
Problem
As a programming exercise I made a square root function in C# using recursion, here is the function:
It is able to do
static double root(double x, double increment, double num)
{
num += increment;
if ((num * num).ToString() == x.ToString())
return num;
else if (num * num x)
return root(x, Math.Abs(increment / 2) * -1, num);
else
return double.NaN;
}
static double sqroot(double x)
{
return root(x, 10, 0);
}It is able to do
int.MaxValue without a problem, but my question is, how can this be improved?Solution
A couple of things.
Is the string conversions really necessary just for comparing 2 doubles?
Figuring the squared value on the fly seems to lead to a bit of repetition
Also, optional parameters make the initial calling simpler.
Since it appears that integers will introduce rounding errors, you filter for that by checking if the difference is less than or equal to 0.000000000000001, instead of just equal to, which gives the same degree of accuracy in the final answer as the built-in sqrt method of the Math class.
Is the string conversions really necessary just for comparing 2 doubles?
Figuring the squared value on the fly seems to lead to a bit of repetition
Also, optional parameters make the initial calling simpler.
static double root(double x, double increment = 10, double num = 0)
{
num += increment;
double sqrdValue = num * num;
if (sqrdValue == x)
return num;
else if (sqrdValue x)
return root(x, Math.Abs(increment / 2) * -1, num);
else
return double.NaN;
}Since it appears that integers will introduce rounding errors, you filter for that by checking if the difference is less than or equal to 0.000000000000001, instead of just equal to, which gives the same degree of accuracy in the final answer as the built-in sqrt method of the Math class.
static double root(double x, double increment = 10, double num = 0)
{
double maxError = 0.000000000000001;
num += increment;
double sqrdValue = num * num;
if (Math.Abs(sqrdValue - x) x)
return root(x, Math.Abs(increment / 2) * -1, num);
else
return double.NaN;
}Code Snippets
static double root(double x, double increment = 10, double num = 0)
{
num += increment;
double sqrdValue = num * num;
if (sqrdValue == x)
return num;
else if (sqrdValue < x)
return root(x, Math.Abs(increment), num);
else if (sqrdValue > x)
return root(x, Math.Abs(increment / 2) * -1, num);
else
return double.NaN;
}static double root(double x, double increment = 10, double num = 0)
{
double maxError = 0.000000000000001;
num += increment;
double sqrdValue = num * num;
if (Math.Abs(sqrdValue - x) <= maxError)
return num;
else if (sqrdValue < x)
return root(x, Math.Abs(increment), num);
else if (sqrdValue > x)
return root(x, Math.Abs(increment / 2) * -1, num);
else
return double.NaN;
}Context
StackExchange Code Review Q#145981, answer score: 5
Revisions (0)
No revisions yet.