Skip to content

Instantly share code, notes, and snippets.

@WardCunningham
Last active August 29, 2015 14:02
Show Gist options
  • Save WardCunningham/6165de4c06a7590e3c9d to your computer and use it in GitHub Desktop.
Save WardCunningham/6165de4c06a7590e3c9d to your computer and use it in GitHub Desktop.
Reliable Representation of Integers in Floats
#include <iostream>
int main() {
int n = 0;
for (long w=1; w<=10000000000000L; w*=10) {
int k = 0;
for (int i=0; i<1000000; i++) {
long p = (long)(rand()%w);
long q = (float) p;
if (p != q) k++;
}
std::cout << "\n";
std::cout << n++ << "\n";
std::cout << w-1 << "\n";
std::cout << (long)(rand()%w) << "\n";
std::cout << k << "\n";
}
}
class FloatPrecisionTest {
public static void main(String[] args) {
int n = 0;
for (long w=1; w<=10000000000000L; w*=2) {
int k = 0;
for (int i=0; i<1000000; i++) {
long p = (long)(Math.random()*w);
long q = (long)(float) p;
if (p != q) k++;
}
System.out.println();
System.out.println(n++);
System.out.println(w-1);
System.out.println((long)(Math.random()*w));
System.out.println(k);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment