Skip to content

Instantly share code, notes, and snippets.

@fabiogaluppo
Last active December 9, 2015 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabiogaluppo/6e8a7464fab8c1cdc515 to your computer and use it in GitHub Desktop.
Save fabiogaluppo/6e8a7464fab8c1cdc515 to your computer and use it in GitHub Desktop.
#include <cmath>
#include <limits>
void commutative_and_epsilon()
{
double a = 1.0, b = 2.0, c = 3.0;
if (((a + b) + c) == (a + (b + c))) //or: if ((a + b + c) == (c + b + a))
std::cout << "commutative holds\n";
else
std::cout << "commutative NOT holds\n";
a = 0.1, b = 0.2, c = 3.0;
if (((a + b) + c) == (a + (b + c))) //or: if ((a + b + c) == (c + b + a))
std::cout << "commutative holds\n";
else
std::cout << "commutative NOT holds\n";
double x = (a + b) + c, y = a + (b + c); //or: double x = a + b + c, y = c + b + a;
double delta = std::abs(x - y);
//double eps = std::numeric_limits<double>::epsilon();
double eps = (1022 - 52 + 1) * std::pow(2, 52); //http://stackoverflow.com/questions/13698927/compare-double-to-zero-using-epsilon
if (delta <= eps)
std::cout << "commutative holds\n";
else
std::cout << "commutative NOT holds\n";
//For more elaborated explanation:
//https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
}
/*
commutative holds
commutative NOT holds
commutative holds
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment