0

Wondering why does Guava use bitwise to calculate avg between 2 values (mean)?
I've run the benchmark on the 2 methods and they seem very similar in performance.

// non-bitwise
int avg = x + (y - x) / 2;
// bitwise
int avg = (x & y) + ((x ^ y) >> 1);
wayne
  • 598
  • 3
  • 15
  • Which `meanRoundDown` are you asking about? Please provide a link to the javadoc or source code. – Stephen C Mar 19 '22 at 11:58
  • duplicates: [Using bit manipulation to calculate the mean value of two number?](https://stackoverflow.com/q/44109340/995714), [Explanation of the safe average of two numbers](https://stackoverflow.com/q/19106350/995714) – phuclv Mar 19 '22 at 12:02
  • 2
    Try `x = Integer.MAX_VALUE` and `y = Integer.MIN_VALUE`, and you'll see why the non bitwise has problems. The problem with add and subtract is that you can overflow or underflow. So, use something that is safe. – Olivier Grégoire Mar 19 '22 at 13:32
  • Whoever downvoted, I really find no reason to do. – Nikolas Charalambidis Mar 19 '22 at 14:18

0 Answers0