Commons Math
  1. Commons Math
  2. MATH-1035

Better implementation of checked addition

    Details

    • Type: Improvement Improvement
    • Status: Resolved
    • Priority: Minor 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.

        Activity

        Hide
        Thomas Neidhart added a comment -

        guava has similar code (adapted to commons-math):

                 final long result = a + b;
                 if (!((a ^ b) < 0 | (a ^ result) >= 0)) {
                     throw new MathArithmeticException(pattern, a, b);
                 }
                 return result;
        
        Show
        Thomas Neidhart added a comment - guava has similar code (adapted to commons-math): final long result = a + b; if (!((a ^ b) < 0 | (a ^ result) >= 0)) { throw new MathArithmeticException(pattern, a, b); } return result;
        Hide
        Thomas Neidhart added a comment -

        Applied change in r1533643 together with a few more tests.

        Show
        Thomas Neidhart added a comment - Applied change in r1533643 together with a few more tests.

          People

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

            Dates

            • Created:
              Updated:
              Resolved:

              Development