Skip to content

Instantly share code, notes, and snippets.

@awade
Created January 24, 2019 21:23
Show Gist options
  • Save awade/0c390496a595a4c4d94be532e23fd577 to your computer and use it in GitHub Desktop.
Save awade/0c390496a595a4c4d94be532e23fd577 to your computer and use it in GitHub Desktop.
Simple implementation of python code (using numpy) for rounding numbers using probabilistic rounding on the last digit. Should be able to handle pos and neg values but not arrays.
def truncFloat(x,dp):
'''Truncates a numpy float to given decimal places (dp)'''
return np.trunc(x * 10 ** dp) / 10 ** dp
def probRound(x, dp):
'''Rounds float to given decimal places (dp), with
last digit round done on a probablistic basis.'''
xTrunc = truncFloat(x, dp) # Truncate to dp figures
xrem = x - xTrunc # find remainder of truncation
p = np.abs(xrem) * 10 ** dd # prob of rounding up based on trunc remainder
if np.random.uniform(0,1) < p:
xout = xTrunc + np.sign(x) * 10 ** -dd
else:
xout = xTrunc
return xout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment