-
-
Save fabiogaluppo/6e8a7464fab8c1cdc515 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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