fork download
  1. /* Problem 10.* Comparing Floats
  2. Write a program that safely compares floating-point numbers (double) with precision eps = 0.000001. Note that
  3. we cannot directly compare two floating-point numbers a and b by a==b because of the nature of the floating-point
  4. arithmetic. Therefore, we assume two numbers are equal if they are more closely to each other than a fixed
  5. constant eps. Examples:
  6.  
  7. Number a Number b Equal (with precision eps=0.000001) Explanation
  8. 5.3 6.01 false The difference of 0.71 is too big (> eps)
  9. 5.00000001 5.00000003 true The difference 0.00000002 < eps
  10. 5.00000005 5.00000001 true The difference 0.00000004 < eps
  11. -0.0000007 0.00000007 true The difference 0.00000077 < eps
  12. -4.999999 -4.999998 false Border case. The difference 0.000001 == eps.
  13. We consider the numbers are different.
  14. 4.999999 4.999998 false Border case. The difference 0.000001 == eps.
  15. We consider the numbers are different.
  16.   */
  17.  
  18. #include <stdio.h>
  19.  
  20. int compareFloats(float a, float b) {
  21.  
  22. float eps = 0.000001;
  23. float diff;
  24.  
  25. if (a > b)
  26. diff = a - b;
  27. else
  28. diff = b - a;
  29.  
  30. printf("Floats %f and %f are ", a, b);
  31. if (diff >= eps)
  32. printf("not");
  33. printf(" equal (with precision eps=0.000001) ");
  34. }
  35.  
  36. int main(void) {
  37.  
  38. compareFloats(5.3,6.01);
  39. compareFloats(5.00000001,5.00000003);
  40. compareFloats(5.00000005,5.00000001);
  41. compareFloats(-0.0000007,0.00000007);
  42. compareFloats(-4.999999,-4.999998);
  43. compareFloats(4.999999,4.999998);
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0s 2112KB
stdin
Standard input is empty
stdout
Floats 5.300000 and 6.010000 are not equal (with precision eps=0.000001) Floats 5.000000 and 5.000000 are  equal (with precision eps=0.000001) Floats 5.000000 and 5.000000 are  equal (with precision eps=0.000001) Floats -0.000001 and 0.000000 are  equal (with precision eps=0.000001) Floats -4.999999 and -4.999998 are  equal (with precision eps=0.000001) Floats 4.999999 and 4.999998 are  equal (with precision eps=0.000001)