Skip to content

Instantly share code, notes, and snippets.

@Mygod
Created September 22, 2016 02:30
Show Gist options
  • Save Mygod/f6f51abaded834e4ce095e82fb808995 to your computer and use it in GitHub Desktop.
Save Mygod/f6f51abaded834e4ce095e82fb808995 to your computer and use it in GitHub Desktop.
Proof that float multiplication is not associative
#include <iostream>
#include <random>
using namespace std;
int main() {
random_device dev;
default_random_engine engine(dev());
uniform_int_distribution<int> dist(0, 99999999);
int x, y, z, count = 0;
double dx, dy, dz;
for (;;) {
++count;
dx = x = dist(engine);
dy = y = dist(engine);
dz = z = dist(engine);
if (dx * dy * dz != dz * dy * dx) {
cout.precision(17);
cout << x << ',' << y << ',' << z << " after " << count << " iterations." << endl;
cout << "dx * dy * dz = " << dx * dy * dz << endl;
cout << "dz * dy * dx = " << dz * dy * dx << endl;
return 0;
}
}
}
@Mygod
Copy link
Author

Mygod commented Sep 22, 2016

Sample run:

98263439,98702733,16852388 after 1013 iterations.
dx * dy * dz = 1.6344912011976766e+23
dz * dy * dx = 1.6344912011976762e+23

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment