Instantly share code, notes, and snippets.

# fabiogaluppo/gist:6e8a7464fab8c1cdc515Secret Last active Dec 9, 2015

 #include #include 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::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 */