Stochastic rounding

PHOTO EMBED

Thu Feb 17 2022 12:49:49 GMT+0000 (Coordinated Universal Time)

Saved by @Ruben_Guerrero #c++ #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;
}
content_copyCOPY

Rounding as follows to one of the closest integer toward negative infinity and the closest integer toward positive infinity, with a probability dependent on the proximity is called stochastic rounding and will give an unbiased result on average.