Resharper wants me to change this existing code:
if (pic.Height == oldH)
{
pic.Height *= fX;
}
...to this:
if (Math.Abs(pic.Height - oldH) < TOLERANCE)
{
pic.Height *= fX;
}
...because "Comparison of floating point numbers with equality operator. Possible loss of precision while rounding values"
The "guttersnipe" (the tooltip that pops up when hovering over Resharper's light bulb icon to the left of the code) is "Fix floating point numbers comparing. Compare a difference with Epsilon"
The code has worked for months without problems; I'm glad to make it better by using the Resharpened version of the code but: what should the value of the Epsilon ("TOLERANCE") be?
Here is the code in full:
internal static void ScalePicture(Picture pic, double width, double height)
{
var fX = width / pic.Width;
var fY = height / pic.Height;
var oldH = pic.Height;
if (fX < fY)
{
pic.Width *= fX;
if (pic.Height == oldH)
{
pic.Height *= fX;
}
pic.Top += (height - pic.Height) / 2;
}
else
{
pic.Width *= fY;
if (pic.Height == oldH)
{
pic.Height *= fY;
}
pic.Left += (width - pic.Width) / 2;
}
}
Would something like this be reasonable:
const double TOLERANCE = 0.001;
?
Note: Consistently, R# also wants the second "if (pic.Height == oldH)" to be compared to TOLERANCE.
I use this code for comparing doubles after doing some research on the web.
public static bool EqualInPercentRange(this double Value1, double Value2, long Units = 2) {
long longValue1 = BitConverter.DoubleToInt64Bits(Value1);
long longValue2 = BitConverter.DoubleToInt64Bits(Value2);
//
// If the signs are different, return false except for +0 and -0.
//
if ((longValue1 >> 63) != (longValue2 >> 63)) {
//
// ReSharper disable once CompareOfFloatsByEqualityOperator
//
return Value1 == Value2;
}
long diff = Math.Abs(longValue1 - longValue2);
return diff <= Units;
}
Original Source on MSDN: https://msdn.microsoft.com/en-us/library/ya2zha7s%28v=vs.110%29.aspx