Skip to content

Instantly share code, notes, and snippets.

@coleoguy
Created April 30, 2016 19:20
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 coleoguy/a50dba496fc55440cb4945fe8e25d703 to your computer and use it in GitHub Desktop.
Save coleoguy/a50dba496fc55440cb4945fe8e25d703 to your computer and use it in GitHub Desktop.
stochastic rounding
StochRound <- function(x){
## extract the decimal portion
q <- abs(x - trunc(x))
## draw a value 0 or 1 with probability
## based on how close we already are
adj <- sample(0:1, size = 1, prob = c(1 - q, q))
## make it negative if x is
if(x < 0) adj <- adj * -1
## return our new value
trunc(x) + adj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment