Created
January 24, 2019 21:23
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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