Skip to content

Instantly share code, notes, and snippets.

@plesner
Last active August 29, 2015 14:09
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 plesner/7a13b5c8d269315df645 to your computer and use it in GitHub Desktop.
Save plesner/7a13b5c8d269315df645 to your computer and use it in GitHub Desktop.
Simple experiment with floating-point rounding modes in C
#include <fenv.h>
#include <stdio.h>
#include <stdlib.h>
double do_the_thing(const char *mode) {
float b, v;
int i;
b = 0.01;
// Perform a lot of operations on b to accumulate rounding.
for (i = 0; i < 100000; i++)
b *= 1.00001;
v = 0.1 - b;
printf("%s %f\n", mode, v);
return v;
}
int main(int argc, char *argv[]) {
do_the_thing("round default: ");
fesetround(FE_UPWARD);
do_the_thing("round up: ");
fesetround(FE_DOWNWARD);
do_the_thing("round down: ");
return 0;
}
// gcc -O0 test.c -Wall -lm && ./a.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment