Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#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