Sonst werden besonders kleine Zahlen Grundsätzlich als ähnlich angesehen, selbst wenn sie relativ gesehen sehr unterschiedlich sind.
Hier mein Vorschlag:
public static readonly double Epsilon = Math.Pow(2d, -52d);
public static bool IsEqualTo(this double value, double other) { return IsEqualTo(value, other, Epsilon); }
public static bool IsEqualTo(this double value, double other, double absEps)
{
var specialCase = CheckSpecialCases(value, other);
if (specialCase.HasValue) return specialCase.Value;
if (value ≥ .0)
{
if (other ≥ .0)
return value > other
? (value - other) / value < Epsilon
: (other - value) / other < Epsilon;
}
else if (other < .0)
return value > other
? (other - value) / other < Epsilon
: (value - other) / value < Epsilon;
return Math.Abs(value - other) < absEps;
}
private static bool? CheckSpecialCases(double value, double other)
{
if (value == other) return true;
if (double.IsNaN(value)) return double.IsNaN(other);
if (double.IsNegativeInfinity(value)) return double.IsNegativeInfinity(other);
if (double.IsPositiveInfinity(value)) return double.IsPositiveInfinity(other);
if (double.IsNaN(other) || double.IsInfinity(other)) return false;
return null;
}
Gruß
T-Man