/RoundingDemo

Trying to see the effects of Bankers' Rounding

Primary LanguagePythonMIT LicenseMIT

RoundingDemo

After seeing https://stackoverflow.com/questions/977796/why-does-math-round2-5-return-2-instead-of-3-in-c I wanted to see the effects of Banker's Rounding.

Banker's Rounding, also known as rounding half to even results in smaller error when averaging and summing rounded values than rounding half up. The improvement is clearly visible for experiments with large sample numbers, for example, more than 100.

rounding.py creates a lot of random decimals with one digit after the decimal point. Then it calculates a sum and an average for all three of:

  • original random decimals
  • values rounded half to even
  • values rounded half up

Then, the script calculates percentage error and plots distribution of numbers.

Usage

rounding.py [-h] [--plot [PLOT]] [--seed [SEED]]
               [domainMin] [domainMax] [samples]

All arguments have default values and all can be changed. rounding.py -h explains each argument in greater detail.

Sample usage:

$ python rounding.py
$ python rounding.py -5 5 300
$ python rounding.py 10000 20000 100000 --plot 0

Results

Example with varying number of samples:

Domain: x in [ 0 , 4 ], dx = 0.1. Number of samples: 50
Actual average: 1.86
Average after rounding half to even: 1.8 . Error = 3.33333333333 %
Average after rounding half up: 1.9 . Error = 2.10526315789 %
Actual sum: 93.0
Sum after rounding half to even: 90.0 . Error = 3.33333333333 %
Sum after rounding half up: 95.0 . Error = 2.10526315789 %
Here, rounding half up is a better method

Domain: x in [ 0 , 4 ], dx = 0.1. Number of samples: 200
Actual average: 2.07
Average after rounding half to even: 2.065 . Error = 0.242130750605 %
Average after rounding half up: 2.115 . Error = 2.12765957447 %
Actual sum: 414.0
Sum after rounding half to even: 413.0 . Error = 0.242130750605 %
Sum after rounding half up: 423.0 . Error = 2.12765957447 %
Here, rounding half to even is a better method

Domain: x in [ 0 , 4 ], dx = 0.1. Number of samples: 2000
Actual average: 1.9737
Average after rounding half to even: 1.985 . Error = 0.569269521411 %
Average after rounding half up: 2.025 . Error = 2.53333333333 %
Actual sum: 3947.4
Sum after rounding half to even: 3970.0 . Error = 0.569269521411 %
Sum after rounding half up: 4050.0 . Error = 2.53333333333 %
Here, rounding half to even is a better method

Example with negative numbers:

Domain: x in [ -5 , 5 ], dx = 0.1. Number of samples: 100
Actual average: -0.225
Average after rounding half to even: -0.24 . Error = -6.25 %
Average after rounding half up: -0.28 . Error = -19.6428571429 %
Actual sum: -22.5
Sum after rounding half to even: -24.0 . Error = -6.25 %
Sum after rounding half up: -28.0 . Error = -19.6428571429 %
Here, rounding half to even is a better method

```