Skip to content

Instantly share code, notes, and snippets.

@minghz
Created August 7, 2018 03:48
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 minghz/7cf85fd6db687f48fb95364a476ae375 to your computer and use it in GitHub Desktop.
Save minghz/7cf85fd6db687f48fb95364a476ae375 to your computer and use it in GitHub Desktop.
Example function for stochastic rounding in C++
float rstoc(x) {
float decimal = abs(x - trunc(x));
float random_selector = (float)rand() / RAND_MAX;
float adjustor;
if (random_selector < decimal) adjustor = 1;
else adjustor = 0;
// consider sign
if(x < 0) adjustor = -1 * adjustor;
return trunc(x) + adjustor;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment