# floating_point_equality.c

Sep 23rd, 2020
131
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*
2.
3.     floating_point_equality.c
4.
5.     https://www.learncpp.com/cpp-tutorial/relational-operators-and-floating-point-comparisons/
6.
7.
8.     You can find all my C++ programs at Dragan Milicev's pastebin:
9.
10.     https://pastebin.com/u/dmilicev
11.
12. */
13.
14. #include <stdio.h>
15.
16. // returns largest value from given two values x and y
17. double double_max( double x, double y)
18. {
19.     if(x>y)
20.         return x;
21.
22.     return y;
23. }
24.
25. // returns absolute value of x
26. double double_abs( double x)
27. {
28. //printf("\n In double_abs x = %.16lf \n", x);
29.
30.     if(x<0)
31.         return (-x);
32.
33.     return x;
34. }
35.
36. // return true if the difference between a and b is
37. // within epsilon percent of the larger of a and b
38. int isApproximatelyEqualAbs(double a, double b, double absEpsilon)
39. {
40.     return ( double_abs(a - b) <= ( double_max(double_abs(a), double_abs(b)) * absEpsilon) );
41. }
42.
43. int isApproximatelyEqualAbsRel(double a, double b, double absEpsilon, double relEpsilon)
44. {
45.     // Check if the numbers are really close, needed when comparing numbers near zero.
46.     double diff = double_abs(a-b);
47.
48.     printf("\n diff = %.8lf \n", diff);
49.
50.     if (diff <= absEpsilon)
51.     {
52.         printf("\n 1, absEpsilon \n");
53.         return 1;
54.     }
55.
56.     // Otherwise fall back to Knuth's algorithm
57.     printf("\n 2, relEpsilon \n");
58.     return( diff <= ( double_max(double_abs(a),double_abs(b)) * relEpsilon ) );
59. }
60.
61.
62. int main()
63. {
64.     double a = 123.456789;
65.     double b = 123.456779;
66.
67.     printf("\n   a = %lf \n", a);
68.     printf("\n   b = %lf \n", b);
69.     printf("\n 1e-8 = %.8lf \n", 1e-8);
70.
71.     // compare a and b
72.     printf("\n isApproximatelyEqualAbs(a, b, 1e-8) = %d \n",
73.             isApproximatelyEqualAbs(a, b, 1e-8) );
74.
75.     // compare a and b
76.     printf("\n isApproximatelyEqualAbsRel(a, b, 1e-8, 1e-8) = %d \n",
77.             isApproximatelyEqualAbsRel(a, b, 1e-8, 1e-8) );
78.
79.
80.     return 0;
81. }
82.
RAW Paste Data Copied