3 ms·
Calculating (a+b)/2 isn't even entirely trivial for integers - the trivial implementation overflows on large numbers, as one may find out when doing a binary se
by praptak 8y ago
Calculating (a+b)/2 isn't even entirely trivial for integers - the trivial implementation overflows on large numbers, as one may find out when doing a binary search over a 4GB array.
- vortico 8y ago`(uint32_t) (((uint64_t) a + (uint64_t) b) / 2)` and then go on with your life. :P
- adrianmonk 8y agoAlso, their overflow avoidance technique fails on integers too, and for basically the same reason (lack of precision). Suppose you want to find the mean of (1, 1, 1). If you divide by the length of the list first, you're going to compute sum(1/3, 1/3, 1/3), which reduces to sum(0, 0, 0). And 0 < min(1, 1, 1).