Hacker News new | ask | show | jobs
by praptak 2651 days 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.
2 comments

Also, 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).

`(uint32_t) (((uint64_t) a + (uint64_t) b) / 2)` and then go on with your life. :P