Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tvwerkhoven
Created June 23, 2011 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvwerkhoven/1042411 to your computer and use it in GitHub Desktop.
Save tvwerkhoven/1042411 to your computer and use it in GitHub Desktop.
Machine precision test
/* add_test.c -- test machine precision for float and double datatypes
Compile: gcc -lm add_test.c -o add_test
Adapted from: http://virtuallyshocking.com/2008/01/14/float-vs-double/
This code iteratively increments a Real variable with a small amount,
leading to round-off errors. When the round-off error is bigger than
a preset value 'diff', it prints the number of iterations and the round-off
error at that point. Additionally it prints the error at each 100 iterations.
This tests three combinations of machine precision:
* Float counter with float increment
* Double counter with double increment
* Double counter with float increment
*/
#include <stdio.h>
#include <math.h>
int main (void) {
float float_v=0, fdt;
double double_v=0, cross_v=0, ddt, diff;
int i;
ddt = 1e-5;
fdt = 1e-5;
diff = 1e-8;
for (i=1; i< 1e6; i++) {
double_v += ddt;
float_v += fdt;
cross_v += fdt;
if (i % 100 == 0) {
printf("%d: float: %.3g, dbl: %.3g, cross: %.3g, diff: %g\n",
i,
fabs(float_v - i*ddt),
fabs(double_v - i*ddt),
fabs(cross_v - i*ddt),
double_v - float_v);
}
if (fabs(double_v - float_v) > diff) {
printf("Found discrepancy of %g at step %d!\n", double_v - float_v, i);
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment