in reply to Re: How to calculate the sum of columns to be equal to 100?
in thread How to calculate the sum of columns to be equal to 100?
One floating-point technique that is sometimes used is called banker’s rounding,” which rounds even-ending numbers one way, odd-ending numbers the other. (I don’t rightly recall if Perl implements it.)
Yes, Perl implements it, because it uses C libraries which implement the rounding recommended by IEEE.
The idea is the following. Suppose, to take a simple case, that you want to round to the unit numbers which have only one decimal digit. Any number where the decimal digit is less than 5 will be rounded down and any number where the decimal digit is larger than 5 is rounded up. But what do you do if the decimal part is exactly 5? Say, for example, how do you round 3.5? The most usual method rounds such a number up. But bankers claim that this introduces a bias towards rounding up: out of ten possible decimal digits, one will not be rounded (0), 4 will be rounded down (1, 2, 3 and 4) and 5 will be rounded up (5 to 9). This can make a difference if you add a long series of numbers. So they decided that the rounding of the 5 decimal digit will be rounded up or down, depending on whether the previous digit is odd or even.
This is what you can see in the somewhat strange output of a Perl one-liner below:
$ perl -e 'print "raw\t\trounded\n"; printf "%f\t%.0f\n", $_+0.5, $_+ +0.5 for 0..10; ' raw rounded 0.500000 0 1.500000 2 2.500000 2 3.500000 4 4.500000 4 5.500000 6 6.500000 6 7.500000 8 8.500000 8 9.500000 10 10.500000 10
I actually once had to write a special rounding module just because my client considered the above to be simply wrong and wanted 2.5 to be rounded to 3.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: How to calculate the sum of columns to be equal to 100?
by Athanasius (Archbishop) on Aug 15, 2013 at 15:33 UTC | |
by Laurent_R (Canon) on Aug 15, 2013 at 18:53 UTC | |
by Laurent_R (Canon) on Aug 15, 2013 at 18:03 UTC | |
by Athanasius (Archbishop) on Aug 16, 2013 at 02:27 UTC |