Uploaded image for project: 'Commons Math'
  1. Commons Math
  2. MATH-1035

Better implementation of checked addition

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Minor
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 3.3
    • Labels:
      None

      Description

      The implementation of org.apache.commons.math3.util.ArithmeticUtils.addAndCheck(long, long, Localizable) is inefficient and confusing. Here's a better way:

      private static long addAndCheck(long a, long b, Localizable pattern) throws MathArithmeticException {
          final long SIGN_BIT = 1L << 63;
          long result = a + b;
          // If a and b have opposite sign, the result will not overflow.
          // If a and b have the same sign, the result overflowed if it has different sign.
          if (((~(a ^ b)) & (a ^ result) & SIGN_BIT) != 0) {
              throw new MathArithmeticException(pattern, a, b);
          }
          return result;
      }
      

      This bug tracker is bad btw. It raped my browser.

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              derphead derphead
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: