commons-issues mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Thomas Neidhart (JIRA)" <j...@apache.org>
Subject [jira] [Commented] (MATH-1035) Better implementation of checked addition
Date Fri, 11 Oct 2013 21:18:42 GMT

    [ https://issues.apache.org/jira/browse/MATH-1035?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13793055#comment-13793055
] 

Thomas Neidhart commented on MATH-1035:
---------------------------------------

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

{noformat}
         final long result = a + b;
         if (!((a ^ b) < 0 | (a ^ result) >= 0)) {
             throw new MathArithmeticException(pattern, a, b);
         }
         return result;
{noformat}

> Better implementation of checked addition
> -----------------------------------------
>
>                 Key: MATH-1035
>                 URL: https://issues.apache.org/jira/browse/MATH-1035
>             Project: Commons Math
>          Issue Type: Improvement
>            Reporter: derphead
>            Priority: Minor
>
> The implementation of org.apache.commons.math3.util.ArithmeticUtils.addAndCheck(long,
long, Localizable) is inefficient and confusing. Here's a better way:
> {code}
> 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;
> }
> {code}
> This bug tracker is bad btw. It raped my browser.



--
This message was sent by Atlassian JIRA
(v6.1#6144)

Mime
View raw message