Created
February 27, 2025 08:59
-
-
Save cmin764/3a01aaed26add545aafaa9fc44ad5643 to your computer and use it in GitHub Desktop.
Round values (up/down) while minimizing the aggregated remainder error
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
| import math | |
| class StatefulRounding: | |
| def __init__(self): | |
| self.error = 0.0 # Tracks accumulated rounding error | |
| def round(self, value): | |
| """ | |
| Round a value dynamically based on the accumulated error. | |
| - Uses floor/ceil to bring total error closer to zero. | |
| """ | |
| floored = math.floor(value) | |
| ceiled = math.ceil(value) | |
| # Compute rounding errors for each choice | |
| error_floor = self.error + (floored - value) | |
| error_ceil = self.error + (ceiled - value) | |
| # Choose the rounding that brings accumulated error closer to zero | |
| if abs(error_floor) <= abs(error_ceil): | |
| self.error = error_floor | |
| return floored | |
| else: | |
| self.error = error_ceil | |
| return ceiled | |
| # Example Usage | |
| rounder = StatefulRounding() | |
| values = [927 / 8, 100 / 8, 827 / 8] # [115.875, 12.5, 103.375] | |
| rounded_values = [rounder.round(v) for v in values] | |
| print(rounded_values) # Expected: [116, 13, 103] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment