Skip to content

Instantly share code, notes, and snippets.

@bmcculley
Last active January 12, 2023 18:07
Show Gist options
  • Save bmcculley/568ec4a982646bf65c1f825d0f9e9dc4 to your computer and use it in GitHub Desktop.
Save bmcculley/568ec4a982646bf65c1f825d0f9e9dc4 to your computer and use it in GitHub Desktop.
Visualize the difference of bankers vs. half up vs. half down vs. no rounding averages.
import math
class deciamlRounding():
def __init__(self, nums = [3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 24.5, 25.5]):
self.nums = nums
# hold the averages
self.no_rounding_avg = float(0.0)
self.bankers_rounding_avg = float(0.0)
self.round_up_avg = float(0.0)
self.round_down_avg = float(0.0)
def round_down(self, x):
if (x % 1 > 0.5):
return math.ceil(x)
return math.floor(x)
def round_up(self, x):
if (x % 1 < 0.5):
return math.floor(x)
return math.ceil(x)
def calulate(self):
for num in self.nums:
self.no_rounding_avg += num
self.bankers_rounding_avg += round(num)
self.round_down_avg += self.round_down(num)
self.round_up_avg += self.round_up(num)
self.no_rounding_avg = round(self.no_rounding_avg / len(self.nums), 3)
self.bankers_rounding_avg = round(self.bankers_rounding_avg / len(self.nums), 3)
self.round_up_avg = round(self.round_up_avg / len(self.nums), 3)
self.round_down_avg = round(self.round_down_avg / len(self.nums), 3)
def example_one():
dr = deciamlRounding()
# take a look at the array of numbers
print(dr.nums)
dr.calulate()
# visualize the difference
print("No rounding: %s"% dr.no_rounding_avg)
print("Bankers rounding: %s"% dr.bankers_rounding_avg)
print("Half up rounding: %s"% dr.round_up_avg)
print("Half down rounding: %s"% dr.round_down_avg)
def example_two():
dr = deciamlRounding(nums = [3.4, 4.5, 5.6, 6.4, 7.5, 8.6, 9.4, 10.5, 11.6, 13.4, 14.5, 15.6, 16.4, 17.5, 18.6, 19.4, 20.5, 21.6, 22.4, 24.5, 25.6])
# take a look at the array of numbers
print(dr.nums)
dr.calulate()
# visualize the difference
print("No rounding: %s"% dr.no_rounding_avg)
print("Bankers rounding: %s"% dr.bankers_rounding_avg)
print("Half up rounding: %s"% dr.round_up_avg)
print("Half down rounding: %s"% dr.round_down_avg)
if __name__ == "__main__":
example_one()
example_two()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment