Answer

I would consider this to be tricky question as many people would just go with

if (a == b) or at most a.Equals(b)

but both can fail for float number. The correct answer is to use absolute or relative error and compare with epsilon:

Absolute Error:


double eps = 0.00001;
if (Math.Abs(a - b) < eps)
{
Console.WriteLine("Equal");
}


If the absolute error is too small for the numbers being compared then the epsilon comparison may have no effect, so generic way is to use relative Error:


double eps = 0.00001;
if (Math.Abs((a - b)/b) < eps)
{
Console.WriteLine("Equal");
}


More info:


Comparing floating point numbers by Bruce Dawson








Answers and Comments


Saved Stories

Sponsored Categories