Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- floating_point_equality.c
- https://www.learncpp.com/cpp-tutorial/relational-operators-and-floating-point-comparisons/
- You can find all my C++ programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- // returns largest value from given two values x and y
- double double_max( double x, double y)
- {
- if(x>y)
- return x;
- return y;
- }
- // returns absolute value of x
- double double_abs( double x)
- {
- //printf("\n In double_abs x = %.16lf \n", x);
- if(x<0)
- return (-x);
- return x;
- }
- // return true if the difference between a and b is
- // within epsilon percent of the larger of a and b
- int isApproximatelyEqualAbs(double a, double b, double absEpsilon)
- {
- return ( double_abs(a - b) <= ( double_max(double_abs(a), double_abs(b)) * absEpsilon) );
- }
- int isApproximatelyEqualAbsRel(double a, double b, double absEpsilon, double relEpsilon)
- {
- // Check if the numbers are really close, needed when comparing numbers near zero.
- double diff = double_abs(a-b);
- printf("\n diff = %.8lf \n", diff);
- if (diff <= absEpsilon)
- {
- printf("\n 1, absEpsilon \n");
- return 1;
- }
- // Otherwise fall back to Knuth's algorithm
- printf("\n 2, relEpsilon \n");
- return( diff <= ( double_max(double_abs(a),double_abs(b)) * relEpsilon ) );
- }
- int main()
- {
- double a = 123.456789;
- double b = 123.456779;
- printf("\n a = %lf \n", a);
- printf("\n b = %lf \n", b);
- printf("\n 1e-8 = %.8lf \n", 1e-8);
- // compare a and b
- printf("\n isApproximatelyEqualAbs(a, b, 1e-8) = %d \n",
- isApproximatelyEqualAbs(a, b, 1e-8) );
- // compare a and b
- printf("\n isApproximatelyEqualAbsRel(a, b, 1e-8, 1e-8) = %d \n",
- isApproximatelyEqualAbsRel(a, b, 1e-8, 1e-8) );
- return 0;
- }
Add Comment
Please, Sign In to add comment