[math-fun] Average of a few integers
If you compute the average of two unsigned integers via mean = (x+y)/2 then you could lose because of integer overflow on a machine with bounded word size. However (in C language &=AND, ^=XOR) mean = (a&b)+(a^b)/2 will do the computation without overflow and without any IF-test. Rounds result downward to nearest integer if mean is fractional like 1.5. If you have 4 unsigned integers a,b,c,d then you can compute their average via x = (a&b)+((a^b)/2; //mean(a,b) rounded down y = (c|d)-((c^d)/2); //mean(c,d) rounded up (in C language |=OR) mean = (x&y)+((x^y)/2; which works IF you are willing to accept answer perhaps being as much as 0.75 too low and 0.25 too high. If you add 1 to a before starting (and hope this does not overflow!) then these error bounds are shifted to [-0.5, +0.5]. Now for a harder problem: what about the average of 3 unsigned integers? It's quite difficult to do this optimally. IF-tests and division and overflow all are undesirable. -- Warren D. Smith http://RangeVoting.org <-- add your endorsement (by clicking "endorse" as 1st step)
participants (1)
-
Warren Smith