I am trying to account for the errors in double arithmetic in a C# program I am writing, and came up with this first solution that seems to work well for most cases:
double errorMargins = returnDouble * Double.Parse(Unit_Class_Library.Properties.Resources.AcceptedDeviationConstant);
double roundedValue = 0;
for (int i = 1; i <= returnDoubleAsString.Length; i++)
{
roundedValue = RoundToSignificantDigits(returnDouble, i);
if (Math.Abs(roundedValue - returnDouble) < Double.Parse(Unit_Class_Library.Properties.Resources.AcceptedDeviationConstant))
{
returnDouble = roundedValue;
i = returnDoubleAsString.Length;
}
}
return returnDouble;
}
public static double RoundToSignificantDigits(double d, int digits)
{
if (d == 0)
return 0;
bool isNegative = false;
if (d < 0)
isNegative = true;
double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);
double returnValue = scale * Math.Round(d / scale, digits);
if (isNegative)
returnValue = -returnValue;
return returnValue;
}
However, I found that when you convert a number to a string it rounds the number making the above function not work.
For example, when 720.72499999999991 is inputted (with a AcceptedDeviationConstant
of 0.000000001), the double as string would be "720.725" which causes the above loop to exit prematurely and not do its job leaving the number as 720.72499999999991. So what I did was convert the double to a string and then back to a double (the code block below) and this seems to work how I wanted it too, returning 720.725 in the above example.
string returnDoubleAsString = "" + returnDouble;
returnDouble = double.Parse(returnDoubleAsString);
I was wondering if it is okay to just leave it as the second one but it seems "improper" to do it like this. If it is okay in practice, what kind of comment should I leave to make it clear to other programmers what is going on and is there a link I can put in the comment that explains why this works?