Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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:
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",
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);
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.