Created
November 17, 2024 15:36
-
-
Save ninlith/f6a9fd68634b6c2fba9983d8c699f53c to your computer and use it in GitHub Desktop.
Unround decimal numbers.
This file contains 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
""" | |
Reconstructs the numerator of a rounded rational number. | |
All fractions p/q are uniquely identifiable iff abs(q) <= 10**d. | |
Args: | |
x (float): Rounded decimal value. | |
d (int): Maximum decimal places used in rounding. | |
q (int): Denominator of the fraction. | |
r (callable, optional): Rounding function (default is round). | |
Returns: | |
int: The reconstructed numerator if an exact match is found. | |
bool: False if no exact match is found. | |
Examples: | |
unround(0.33, 2, 3)/3 # -> 0.3333333333333333 | |
unround(round(4/11, 1), 1, 11) # -> 4 | |
unround(round(5/11, 1), 1, 11) # -> False | |
""" | |
# ~-n is n-1 and -~n is n+1 | |
unround=lambda x,d,q,r=round:r(~-(p:=r(q*x))/q,d)!=r(p/q,d)!=r(-~p/q,d)and p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment