FloatComparer.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. namespace XGame.Framework.Assertions
  4. {
  5. public class FloatComparer : IEqualityComparer<float>
  6. {
  7. readonly float m_Error;
  8. readonly bool m_Relative;
  9. public static readonly FloatComparer s_ComparerWithDefaultTolerance = new FloatComparer(kEpsilon);
  10. public const float kEpsilon = 0.00001f;
  11. public FloatComparer()
  12. : this(kEpsilon, false)
  13. {
  14. }
  15. public FloatComparer(bool relative)
  16. : this(kEpsilon, relative)
  17. {
  18. }
  19. public FloatComparer(float error)
  20. : this(error, false)
  21. {
  22. }
  23. public FloatComparer(float error, bool relative)
  24. {
  25. m_Error = error;
  26. m_Relative = relative;
  27. }
  28. public bool Equals(float a, float b)
  29. {
  30. return m_Relative ? AreEqualRelative(a, b, m_Error) : AreEqual(a, b, m_Error);
  31. }
  32. public int GetHashCode(float obj)
  33. {
  34. return base.GetHashCode();
  35. }
  36. public static bool AreEqual(Single expected, Single actual, Single error)
  37. {
  38. return Math.Abs(actual - expected) <= error;
  39. }
  40. public static bool AreEqualRelative(Single expected, Single actual, Single error)
  41. {
  42. if (expected == actual) return true;
  43. var absExpected = Math.Abs(expected);
  44. var absActual = Math.Abs(actual);
  45. var relativeError = Math.Abs((actual - expected) / (absExpected > absActual ? absExpected : absActual));
  46. return relativeError <= error;
  47. }
  48. }
  49. }