Search code examples
javadoublelong-integermedian

How can I fix overflow error when numbers can be too big?


How can I fix the overflow error in the below method?

  public static double median(long[] numbers) {
    Arrays.sort(numbers);
    int middle = numbers.length / 2;
    if (numbers.length % 2 == 1) {
      return numbers[middle];
    } else {
      return (numbers[middle - 1] + numbers[middle]) / 2.0;
    }
  }

This line may overflow if the two numbers are too big:

return (numbers[middle - 1] + numbers[middle]) / 2.0;

How to fix this?


Solution

  • This line may overflow if the two numbers are too big:

    return (numbers[middle - 1] + numbers[middle]) / 2.0;
    

    How to fix this?

    The problem arises with the intermediate addition. If you can rely on the elements of numbers to be non-negative, then you can perform the computation without risk of overflow like so:

    return numbers[middle - 1] + (numbers[middle] - numbers[middle - 1]) / 2.0;
    

    as @EricS mentioned in comments.

    If you have to accommodate the full range of long, positive and negative, then you can do this:

    return numbers[middle - 1] / 2.0 + numbers[middle] / 2.0;
    

    Do be aware that double has greater range but less precision than long, in the sense of the number of significant digits each can represent. If you really need to worry about long values at the extreme ends of that type's range, then you should have a think about what effect that precision loss will have on you.