Advertisement
kruncher

Untitled

Feb 13th, 2013
705
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. public static bool CompareAlmostEqual(float x, float y, float epsilon) {
  2.     // Based upon implementation:
  3.     // http://floating-point-gui.de/errors/comparison/
  4.  
  5.     if (x == y)
  6.         return true;
  7.  
  8.     float absX = Math.Abs(x);
  9.     float absY = Math.Abs(y);
  10.     float diff = Math.Abs(x - y);
  11.  
  12.     if (x * y == 0)
  13.         return diff < (epsilon * epsilon);
  14.     else if (absX + absY == diff) // [1]
  15.         return diff < epsilon;
  16.     else
  17.         return diff / (absX + absY) < epsilon;
  18. }
  19.  
  20. // Without [1] the following test fail:
  21. [TestCase( 0.0001f, -0.0001f, 0.000001f )]
  22. [TestCase( 0.000000000001f, -0.000000000001f, 0.000001f )]
  23.  
  24. // With [1] the following test still fails (as expected):
  25. [TestCase( 0.0001f, -0.0001f, 0.000001f )]
  26. // But this one passes:
  27. [TestCase( 0.000000000001f, -0.000000000001f, 0.000001f )]
  28.  
  29.  
  30. // The following tests are still failing:
  31. Assert.False(AlmostEqual(0.000000001f, -float.Epsilon));
  32.   Failed: InvalidNumbersVeryCloseToZero(1E-09, -1.401298E-45)
  33. Assert.False(AlmostEqual(0.000000001f, float.Epsilon));
  34.   Failed: InvalidNumbersVeryCloseToZero(1E-09, 1.401298E-45)
  35. Assert.False(AlmostEqual(float.Epsilon, 0.000000001f));
  36.   Failed: InvalidNumbersVeryCloseToZero(1.401298E-45, 1E-09)
  37. Assert.False(AlmostEqual(-float.Epsilon, 0.000000001f));
  38.   Failed: InvalidNumbersVeryCloseToZero(-1.401298E-45, 1E-09)
  39.  
  40. Assert.False(AlmostEqual(1e25f * float.Epsilon, -1e25f * float.Epsilon, 1e-12f));
  41.   Failed: InvalidNumbersVeryCloseToZeroCustomDelta(1.401298E-20, -1.401298E-20, 1E-12)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement