fork(6) download
  1. using System;
  2.  
  3. public class Example
  4. {
  5. public static void Main()
  6. {
  7. double[] values = {
  8. //12345678901234567
  9. 0.10000000000000001,
  10. 0.10000000000000002
  11. };
  12.  
  13. Console.WriteLine("{0:r} = {1:r}: =:{2} ae:{3} re:{4} hmd1:{5} hmd0:{6}",
  14. values[0], values[1],
  15. values[0].Equals(values[1]),
  16. AlmostEqual(values[0], values[1]),
  17. ReallyEqual(values[0], values[1]),
  18. HasMinimalDifference(values[0], values[1], 1),
  19. HasMinimalDifference(values[0], values[1], 0));
  20. Console.WriteLine();
  21. }
  22.  
  23. public static bool AlmostEqual(double x, double y) {
  24. double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15;
  25. return Math.Abs(x - y) <= epsilon;
  26. }
  27.  
  28. public static bool ReallyEqual(double x, double y) {
  29. return (x == y);
  30. }
  31.  
  32. public static bool HasMinimalDifference(double value1, double value2, int units) {
  33. long lValue1 = BitConverter.DoubleToInt64Bits(value1);
  34. long lValue2 = BitConverter.DoubleToInt64Bits(value2);
  35.  
  36. // If the signs are different, return false except for +0 and -0.
  37. if ((lValue1 >> 63) != (lValue2 >> 63))
  38. {
  39. if (value1 == value2)
  40. return true;
  41.  
  42. return false;
  43. }
  44.  
  45. long diff = Math.Abs(lValue1 - lValue2);
  46. Console.WriteLine("HMD: {0} {1} {2} {3}",
  47. lValue1, lValue2, diff, units);
  48.  
  49. if (diff <= (long) units)
  50. return true;
  51.  
  52. return false;
  53. }
  54.  
  55. }
  56.  
  57.  
  58.  
Success #stdin #stdout 0.04s 34712KB
stdin
Standard input is empty
stdout
HMD: 4591870180066957722 4591870180066957723 1 1
HMD: 4591870180066957722 4591870180066957723 1 0
0.1 = 0.10000000000000002: =:False ae:True re:False hmd1:True hmd0:False