You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "Thomas Neidhart (JIRA)" <ji...@apache.org> on 2013/10/11 23:18:42 UTC
[jira] [Commented] (MATH-1035) Better implementation of checked
addition
[ 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)