Java Code Examples for org.apache.commons.math.MathRuntimeException#createArithmeticException()

The following examples show how to use org.apache.commons.math.MathRuntimeException#createArithmeticException() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Rotation.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Build a rotation from an axis and an angle.
 * <p>We use the convention that angles are oriented according to
 * the effect of the rotation on vectors around the axis. That means
 * that if (i, j, k) is a direct frame and if we first provide +k as
 * the axis and PI/2 as the angle to this constructor, and then
 * {@link #applyTo(Vector3D) apply} the instance to +i, we will get
 * +j.</p>
 * @param axis axis around which to rotate
 * @param angle rotation angle.
 * @exception ArithmeticException if the axis norm is zero
 */
public Rotation(Vector3D axis, double angle) {

  double norm = axis.getNorm();
  if (norm == 0) {
    throw MathRuntimeException.createArithmeticException("zero norm for rotation axis");
  }

  double halfAngle = -0.5 * angle;
  double coeff = Math.sin(halfAngle) / norm;

  q0 = Math.cos (halfAngle);
  q1 = coeff * axis.getX();
  q2 = coeff * axis.getY();
  q3 = coeff * axis.getZ();

}
 
Example 2
Source File: Fraction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the additive inverse of this fraction.
 * @return the negation of this fraction.
 */
public Fraction negate() {
    if (numerator==Integer.MIN_VALUE) {
        throw MathRuntimeException.createArithmeticException("overflow in fraction {0}/{1}, cannot negate",
                                                             numerator, denominator);
    }
    return new Fraction(-numerator, denominator);
}
 
Example 3
Source File: ArrayRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void unitize() throws ArithmeticException {
    final double norm = getNorm();
    if (norm == 0) {
        throw MathRuntimeException.createArithmeticException("cannot normalize a zero norm vector");
    }
    for (int i = 0; i < data.length; i++) {
        data[i] /= norm;
    }
}
 
Example 4
Source File: Fraction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a fraction given the numerator and denominator.  The fraction is
 * reduced to lowest terms.
 * @param num the numerator.
 * @param den the denominator.
 * @throws ArithmeticException if the denominator is <code>zero</code>
 */
public Fraction(int num, int den) {
    if (den == 0) {
        throw MathRuntimeException.createArithmeticException(
              LocalizedFormats.ZERO_DENOMINATOR_IN_FRACTION, num, den);
    }
    if (den < 0) {
        if (num == Integer.MIN_VALUE || den == Integer.MIN_VALUE) {
            throw MathRuntimeException.createArithmeticException(
                  LocalizedFormats.OVERFLOW_IN_FRACTION, num, den);
        }
        num = -num;
        den = -den;
    }
    // reduce numerator and denominator by greatest common denominator.
    final int d = MathUtils.gcd(num, den);
    if (d > 1) {
        num /= d;
        den /= d;
    }

    // move sign to numerator.
    if (den < 0) {
        num = -num;
        den = -den;
    }
    this.numerator   = num;
    this.denominator = den;
}
 
Example 5
Source File: 1_MathUtils.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Normalizes an array to make it sum to a specified value.
 * Returns the result of the transformation <pre>
 *    x |-> x * normalizedSum / sum
 * </pre>
 * applied to each non-NaN element x of the input array, where sum is the
 * sum of the non-NaN entries in the input array.</p>
 *
 * <p>Throws IllegalArgumentException if <code>normalizedSum</code> is infinite
 * or NaN and ArithmeticException if the input array contains any infinite elements
 * or sums to 0</p>
 *
 * <p>Ignores (i.e., copies unchanged to the output array) NaNs in the input array.</p>
 *
 * @param values input array to be normalized
 * @param normalizedSum target sum for the normalized array
 * @return normalized array
 * @throws ArithmeticException if the input array contains infinite elements or sums to zero
 * @throws IllegalArgumentException if the target sum is infinite or NaN
 * @since 2.1
 */
public static double[] normalizeArray(double[] values, double normalizedSum)
  throws ArithmeticException, IllegalArgumentException {
    if (Double.isInfinite(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NORMALIZE_INFINITE);
    }
    if (Double.isNaN(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NORMALIZE_NAN);
    }
    double sum = 0d;
    final int len = values.length;
    double[] out = new double[len];
    for (int i = 0; i < len; i++) {
        if (Double.isInfinite(values[i])) {
            throw MathRuntimeException.createArithmeticException(
                    LocalizedFormats.INFINITE_ARRAY_ELEMENT, values[i], i);
        }
        if (!Double.isNaN(values[i])) {
            sum += values[i];
        }
    }
    if (sum == 0) {
        throw MathRuntimeException.createArithmeticException(LocalizedFormats.ARRAY_SUMS_TO_ZERO);
    }
    for (int i = 0; i < len; i++) {
        if (Double.isNaN(values[i])) {
            out[i] = Double.NaN;
        } else {
            out[i] = values[i] * normalizedSum / sum;
        }
    }
    return out;
}
 
Example 6
Source File: 1_MathUtils.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add two long integers, checking for overflow.
 *
 * @param a an addend
 * @param b an addend
 * @param pattern the pattern to use for any thrown exception.
 * @return the sum <code>a+b</code>
 * @throws ArithmeticException if the result can not be represented as an
 *         long
 * @since 1.2
 */
private static long addAndCheck(long a, long b, Localizable pattern) {
    long ret;
    if (a > b) {
        // use symmetry to reduce boundary cases
        ret = addAndCheck(b, a, pattern);
    } else {
        // assert a <= b

        if (a < 0) {
            if (b < 0) {
                // check for negative overflow
                if (Long.MIN_VALUE - b <= a) {
                    ret = a + b;
                } else {
                    throw MathRuntimeException.createArithmeticException(pattern, a, b);
                }
            } else {
                // opposite sign addition is always safe
                ret = a + b;
            }
        } else {
            // assert a >= 0
            // assert b >= 0

            // check for positive overflow
            if (a <= Long.MAX_VALUE - b) {
                ret = a + b;
            } else {
                throw MathRuntimeException.createArithmeticException(pattern, a, b);
            }
        }
    }
    return ret;
}
 
Example 7
Source File: MathUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Normalizes an array to make it sum to a specified value.
 * Returns the result of the transformation <pre>
 *    x |-> x * normalizedSum / sum
 * </pre>
 * applied to each non-NaN element x of the input array, where sum is the
 * sum of the non-NaN entries in the input array.</p>
 *
 * <p>Throws IllegalArgumentException if <code>normalizedSum</code> is infinite
 * or NaN and ArithmeticException if the input array contains any infinite elements
 * or sums to 0</p>
 *
 * <p>Ignores (i.e., copies unchanged to the output array) NaNs in the input array.</p>
 *
 * @param values input array to be normalized
 * @param normalizedSum target sum for the normalized array
 * @return normalized array
 * @throws ArithmeticException if the input array contains infinite elements or sums to zero
 * @throws IllegalArgumentException if the target sum is infinite or NaN
 * @since 2.1
 */
public static double[] normalizeArray(double[] values, double normalizedSum)
  throws ArithmeticException, IllegalArgumentException {
    if (Double.isInfinite(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                "Cannot normalize to an infinite value");
    }
    if (Double.isNaN(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                "Cannot normalize to NaN");
    }
    double sum = 0d;
    final int len = values.length;
    double[] out = new double[len];
    for (int i = 0; i < len; i++) {
        if (Double.isInfinite(values[i])) {
            throw MathRuntimeException.createArithmeticException(
                    "Array contains an infinite element, {0} at index {1}", values[i], i);
        }
        if (!Double.isNaN(values[i])) {
            sum += values[i];
        }
    }
    if (sum == 0) {
        throw MathRuntimeException.createArithmeticException(
                "Array sums to zero");
    }
    for (int i = 0; i < len; i++) {
        if (Double.isNaN(values[i])) {
            out[i] = Double.NaN;
        } else {
            out[i] = values[i] * normalizedSum / sum;
        }
    }
    return out;
}
 
Example 8
Source File: Cardumen_00120_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Normalizes an array to make it sum to a specified value.
 * Returns the result of the transformation <pre>
 *    x |-> x * normalizedSum / sum
 * </pre>
 * applied to each non-NaN element x of the input array, where sum is the
 * sum of the non-NaN entries in the input array.</p>
 *
 * <p>Throws IllegalArgumentException if <code>normalizedSum</code> is infinite
 * or NaN and ArithmeticException if the input array contains any infinite elements
 * or sums to 0</p>
 *
 * <p>Ignores (i.e., copies unchanged to the output array) NaNs in the input array.</p>
 *
 * @param values input array to be normalized
 * @param normalizedSum target sum for the normalized array
 * @return normalized array
 * @throws ArithmeticException if the input array contains infinite elements or sums to zero
 * @throws IllegalArgumentException if the target sum is infinite or NaN
 * @since 2.1
 */
public static double[] normalizeArray(double[] values, double normalizedSum)
  throws ArithmeticException, IllegalArgumentException {
    if (Double.isInfinite(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NORMALIZE_INFINITE);
    }
    if (Double.isNaN(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NORMALIZE_NAN);
    }
    double sum = 0d;
    final int len = values.length;
    double[] out = new double[len];
    for (int i = 0; i < len; i++) {
        if (Double.isInfinite(values[i])) {
            throw MathRuntimeException.createArithmeticException(
                    LocalizedFormats.INFINITE_ARRAY_ELEMENT, values[i], i);
        }
        if (!Double.isNaN(values[i])) {
            sum += values[i];
        }
    }
    if (sum == 0) {
        throw MathRuntimeException.createArithmeticException(LocalizedFormats.ARRAY_SUMS_TO_ZERO);
    }
    for (int i = 0; i < len; i++) {
        if (Double.isNaN(values[i])) {
            out[i] = Double.NaN;
        } else {
            out[i] = values[i] * normalizedSum / sum;
        }
    }
    return out;
}
 
Example 9
Source File: Fraction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a fraction given the numerator and denominator.  The fraction is
 * reduced to lowest terms.
 * @param num the numerator.
 * @param den the denominator.
 * @throws ArithmeticException if the denominator is <code>zero</code>
 */
public Fraction(int num, int den) {
    if (den == 0) {
        throw MathRuntimeException.createArithmeticException("zero denominator in fraction {0}/{1}",
                                                             num, den);
    }
    if (den < 0) {
        if (num == Integer.MIN_VALUE || den == Integer.MIN_VALUE) {
            throw MathRuntimeException.createArithmeticException("overflow in fraction {0}/{1}, cannot negate",
                                                                 num, den);
        }
        num = -num;
        den = -den;
    }
    // reduce numerator and denominator by greatest common denominator.
    final int d = MathUtils.gcd(num, den);
    if (d > 1) {
        num /= d;
        den /= d;
    }
    
    // move sign to numerator.
    if (den < 0) {
        num = -num;
        den = -den;
    }
    this.numerator   = num;
    this.denominator = den;
}
 
Example 10
Source File: Math_63_MathUtils_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Normalizes an array to make it sum to a specified value.
 * Returns the result of the transformation <pre>
 *    x |-> x * normalizedSum / sum
 * </pre>
 * applied to each non-NaN element x of the input array, where sum is the
 * sum of the non-NaN entries in the input array.</p>
 *
 * <p>Throws IllegalArgumentException if <code>normalizedSum</code> is infinite
 * or NaN and ArithmeticException if the input array contains any infinite elements
 * or sums to 0</p>
 *
 * <p>Ignores (i.e., copies unchanged to the output array) NaNs in the input array.</p>
 *
 * @param values input array to be normalized
 * @param normalizedSum target sum for the normalized array
 * @return normalized array
 * @throws ArithmeticException if the input array contains infinite elements or sums to zero
 * @throws IllegalArgumentException if the target sum is infinite or NaN
 * @since 2.1
 */
public static double[] normalizeArray(double[] values, double normalizedSum)
  throws ArithmeticException, IllegalArgumentException {
    if (Double.isInfinite(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NORMALIZE_INFINITE);
    }
    if (Double.isNaN(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NORMALIZE_NAN);
    }
    double sum = 0d;
    final int len = values.length;
    double[] out = new double[len];
    for (int i = 0; i < len; i++) {
        if (Double.isInfinite(values[i])) {
            throw MathRuntimeException.createArithmeticException(
                    LocalizedFormats.INFINITE_ARRAY_ELEMENT, values[i], i);
        }
        if (!Double.isNaN(values[i])) {
            sum += values[i];
        }
    }
    if (sum == 0) {
        throw MathRuntimeException.createArithmeticException(LocalizedFormats.ARRAY_SUMS_TO_ZERO);
    }
    for (int i = 0; i < len; i++) {
        if (Double.isNaN(values[i])) {
            out[i] = Double.NaN;
        } else {
            out[i] = values[i] * normalizedSum / sum;
        }
    }
    return out;
}
 
Example 11
Source File: MathUtils.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>
 * Gets the greatest common divisor of the absolute value of two numbers,
 * using the "binary gcd" method which avoids division and modulo
 * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
 * Stein (1961).
 * </p>
 * Special cases:
 * <ul>
 * <li>The invocations
 * <code>gcd(Integer.MIN_VALUE, Integer.MIN_VALUE)</code>,
 * <code>gcd(Integer.MIN_VALUE, 0)</code> and
 * <code>gcd(0, Integer.MIN_VALUE)</code> throw an
 * <code>ArithmeticException</code>, because the result would be 2^31, which
 * is too large for an int value.</li>
 * <li>The result of <code>gcd(x, x)</code>, <code>gcd(0, x)</code> and
 * <code>gcd(x, 0)</code> is the absolute value of <code>x</code>, except
 * for the special cases above.
 * <li>The invocation <code>gcd(0, 0)</code> is the only one which returns
 * <code>0</code>.</li>
 * </ul>
 *
 * @param p any number
 * @param q any number
 * @return the greatest common divisor, never negative
 * @throws ArithmeticException if the result cannot be represented as a
 * nonnegative int value
 * @since 1.1
 */
public static int gcd(final int p, final int q) {
    int u = p;
    int v = q;
    if ((u == 0) || (v == 0)) {
        if ((u == Integer.MIN_VALUE) || (v == Integer.MIN_VALUE)) {
            throw MathRuntimeException.createArithmeticException(
                    "overflow: gcd({0}, {1}) is 2^31",
                    p, q);
        }
        return Math.abs(u) + Math.abs(v);
    }
    // keep u and v negative, as negative integers range down to
    // -2^31, while positive numbers can only be as large as 2^31-1
    // (i.e. we can't necessarily negate a negative number without
    // overflow)
    /* assert u!=0 && v!=0; */
    if (u > 0) {
        u = -u;
    } // make u negative
    if (v > 0) {
        v = -v;
    } // make v negative
    // B1. [Find power of 2]
    int k = 0;
    while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
                                                        // both even...
        u /= 2;
        v /= 2;
        k++; // cast out twos.
    }
    if (k == 31) {
        throw MathRuntimeException.createArithmeticException(
                "overflow: gcd({0}, {1}) is 2^31",
                p, q);
    }
    // B2. Initialize: u and v have been divided by 2^k and at least
    // one is odd.
    int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
    // t negative: u was odd, v may be even (t replaces v)
    // t positive: u was even, v is odd (t replaces u)
    do {
        /* assert u<0 && v<0; */
        // B4/B3: cast out twos from t.
        while ((t & 1) == 0) { // while t is even..
            t /= 2; // cast out twos
        }
        // B5 [reset max(u,v)]
        if (t > 0) {
            u = -t;
        } else {
            v = t;
        }
        // B6/B3. at this point both u and v should be odd.
        t = (v - u) / 2;
        // |u| larger: t positive (replace u)
        // |v| larger: t negative (replace v)
    } while (t != 0);
    return -u * (1 << k); // gcd is u*2^k
}
 
Example 12
Source File: MathUtils.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>
 * Gets the greatest common divisor of the absolute value of two numbers,
 * using the "binary gcd" method which avoids division and modulo
 * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
 * Stein (1961).
 * </p>
 * Special cases:
 * <ul>
 * <li>The invocations
 * <code>gcd(Integer.MIN_VALUE, Integer.MIN_VALUE)</code>,
 * <code>gcd(Integer.MIN_VALUE, 0)</code> and
 * <code>gcd(0, Integer.MIN_VALUE)</code> throw an
 * <code>ArithmeticException</code>, because the result would be 2^31, which
 * is too large for an int value.</li>
 * <li>The result of <code>gcd(x, x)</code>, <code>gcd(0, x)</code> and
 * <code>gcd(x, 0)</code> is the absolute value of <code>x</code>, except
 * for the special cases above.
 * <li>The invocation <code>gcd(0, 0)</code> is the only one which returns
 * <code>0</code>.</li>
 * </ul>
 *
 * @param p any number
 * @param q any number
 * @return the greatest common divisor, never negative
 * @throws ArithmeticException if the result cannot be represented as a
 * nonnegative int value
 * @since 1.1
 */
public static int gcd(final int p, final int q) {
    int u = p;
    int v = q;
    if ((u == 0) || (v == 0)) {
        if ((u == Integer.MIN_VALUE) || (v == Integer.MIN_VALUE)) {
            throw MathRuntimeException.createArithmeticException(
                    "overflow: gcd({0}, {1}) is 2^31",
                    p, q);
        }
        return Math.abs(u) + Math.abs(v);
    }
    // keep u and v negative, as negative integers range down to
    // -2^31, while positive numbers can only be as large as 2^31-1
    // (i.e. we can't necessarily negate a negative number without
    // overflow)
    /* assert u!=0 && v!=0; */
    if (u > 0) {
        u = -u;
    } // make u negative
    if (v > 0) {
        v = -v;
    } // make v negative
    // B1. [Find power of 2]
    int k = 0;
    while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
                                                        // both even...
        u /= 2;
        v /= 2;
        k++; // cast out twos.
    }
    if (k == 31) {
        throw MathRuntimeException.createArithmeticException(
                "overflow: gcd({0}, {1}) is 2^31",
                p, q);
    }
    // B2. Initialize: u and v have been divided by 2^k and at least
    // one is odd.
    int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
    // t negative: u was odd, v may be even (t replaces v)
    // t positive: u was even, v is odd (t replaces u)
    do {
        /* assert u<0 && v<0; */
        // B4/B3: cast out twos from t.
        while ((t & 1) == 0) { // while t is even..
            t /= 2; // cast out twos
        }
        // B5 [reset max(u,v)]
        if (t > 0) {
            u = -t;
        } else {
            v = t;
        }
        // B6/B3. at this point both u and v should be odd.
        t = (v - u) / 2;
        // |u| larger: t positive (replace u)
        // |v| larger: t negative (replace v)
    } while (t != 0);
    return -u * (1 << k); // gcd is u*2^k
}
 
Example 13
Source File: Cardumen_00224_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * <p>
 * Gets the greatest common divisor of the absolute value of two numbers,
 * using the "binary gcd" method which avoids division and modulo
 * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
 * Stein (1961).
 * </p>
 * Special cases:
 * <ul>
 * <li>The invocations
 * <code>gcd(Long.MIN_VALUE, Long.MIN_VALUE)</code>,
 * <code>gcd(Long.MIN_VALUE, 0L)</code> and
 * <code>gcd(0L, Long.MIN_VALUE)</code> throw an
 * <code>ArithmeticException</code>, because the result would be 2^63, which
 * is too large for a long value.</li>
 * <li>The result of <code>gcd(x, x)</code>, <code>gcd(0L, x)</code> and
 * <code>gcd(x, 0L)</code> is the absolute value of <code>x</code>, except
 * for the special cases above.
 * <li>The invocation <code>gcd(0L, 0L)</code> is the only one which returns
 * <code>0L</code>.</li>
 * </ul>
 *
 * @param p any number
 * @param q any number
 * @return the greatest common divisor, never negative
 * @throws ArithmeticException if the result cannot be represented as a nonnegative long
 * value
 * @since 2.1
 */
public static long gcd(final long p, final long q) {
    long u = p;
    long v = q;
    if ((u == 0) || (v == 0)) {
        if ((u == Long.MIN_VALUE) || (v == Long.MIN_VALUE)){
            throw MathRuntimeException.createArithmeticException(
                    LocalizedFormats.GCD_OVERFLOW_64_BITS,
                    p, q);
        }
        return FastMath.abs(u) + FastMath.abs(v);
    }
    // keep u and v negative, as negative integers range down to
    // -2^63, while positive numbers can only be as large as 2^63-1
    // (i.e. we can't necessarily negate a negative number without
    // overflow)
    /* assert u!=0 && v!=0; */
    if (u > 0) {
        u = -u;
    } // make u negative
    if (v > 0) {
        v = -v;
    } // make v negative
    // B1. [Find power of 2]
    int k = 0;
    while ((u & 1) == 0 && (v & 1) == 0 && k < 63) { // while u and v are
                                                        // both even...
        u /= 2;
        v /= 2;
        k++; // cast out twos.
    }
    if (k == 63) {
        throw MathRuntimeException.createArithmeticException(
                LocalizedFormats.GCD_OVERFLOW_64_BITS,
                p, q);
    }
    // B2. Initialize: u and v have been divided by 2^k and at least
    // one is odd.
    long t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
    // t negative: u was odd, v may be even (t replaces v)
    // t positive: u was even, v is odd (t replaces u)
    do {
        /* assert u<0 && v<0; */
        // B4/B3: cast out twos from t.
        while ((t & 1) == 0) { // while t is even..
            t /= 2; // cast out twos
        }
        // B5 [reset max(u,v)]
        if (t > 0) {
            u = -t;
        } else {
            v = t;
        }
        // B6/B3. at this point both u and v should be odd.
        t = (v - u) / 2;
        // |u| larger: t positive (replace u)
        // |v| larger: t negative (replace v)
    } while (t != 0);
    return -u * (1L << k); // gcd is u*2^k
}
 
Example 14
Source File: Cardumen_0053_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * <p>
 * Gets the greatest common divisor of the absolute value of two numbers,
 * using the "binary gcd" method which avoids division and modulo
 * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
 * Stein (1961).
 * </p>
 * Special cases:
 * <ul>
 * <li>The invocations
 * <code>gcd(Integer.MIN_VALUE, Integer.MIN_VALUE)</code>,
 * <code>gcd(Integer.MIN_VALUE, 0)</code> and
 * <code>gcd(0, Integer.MIN_VALUE)</code> throw an
 * <code>ArithmeticException</code>, because the result would be 2^31, which
 * is too large for an int value.</li>
 * <li>The result of <code>gcd(x, x)</code>, <code>gcd(0, x)</code> and
 * <code>gcd(x, 0)</code> is the absolute value of <code>x</code>, except
 * for the special cases above.
 * <li>The invocation <code>gcd(0, 0)</code> is the only one which returns
 * <code>0</code>.</li>
 * </ul>
 *
 * @param p any number
 * @param q any number
 * @return the greatest common divisor, never negative
 * @throws ArithmeticException if the result cannot be represented as a
 * nonnegative int value
 * @since 1.1
 */
public static int gcd(final int p, final int q) {
    int u = p;
    int v = q;
    if ((u == 0) || (v == 0)) {
        if ((u == Integer.MIN_VALUE) || (v == Integer.MIN_VALUE)) {
            throw MathRuntimeException.createArithmeticException(
                    LocalizedFormats.GCD_OVERFLOW_32_BITS,
                    p, q);
        }
        return FastMath.abs(u) + FastMath.abs(v);
    }
    // keep u and v negative, as negative integers range down to
    // -2^31, while positive numbers can only be as large as 2^31-1
    // (i.e. we can't necessarily negate a negative number without
    // overflow)
    /* assert u!=0 && v!=0; */
    if (u > 0) {
        u = -u;
    } // make u negative
    if (v > 0) {
        v = -v;
    } // make v negative
    // B1. [Find power of 2]
    int k = 0;
    while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
                                                        // both even...
        u /= 2;
        v /= 2;
        k++; // cast out twos.
    }
    if (k == 31) {
        throw MathRuntimeException.createArithmeticException(
                LocalizedFormats.GCD_OVERFLOW_32_BITS,
                p, q);
    }
    // B2. Initialize: u and v have been divided by 2^k and at least
    // one is odd.
    int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
    // t negative: u was odd, v may be even (t replaces v)
    // t positive: u was even, v is odd (t replaces u)
    do {
        /* assert u<0 && v<0; */
        // B4/B3: cast out twos from t.
        while ((t & 1) == 0) { // while t is even..
            t /= 2; // cast out twos
        }
        // B5 [reset max(u,v)]
        if (t > 0) {
            u = -t;
        } else {
            v = t;
        }
        // B6/B3. at this point both u and v should be odd.
        t = (v - u) / 2;
        // |u| larger: t positive (replace u)
        // |v| larger: t negative (replace v)
    } while (t != 0);
    return -u * (1 << k); // gcd is u*2^k
}
 
Example 15
Source File: Math_79_MathUtils_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * <p>
 * Gets the greatest common divisor of the absolute value of two numbers,
 * using the "binary gcd" method which avoids division and modulo
 * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
 * Stein (1961).
 * </p>
 * Special cases:
 * <ul>
 * <li>The invocations
 * <code>gcd(Integer.MIN_VALUE, Integer.MIN_VALUE)</code>,
 * <code>gcd(Integer.MIN_VALUE, 0)</code> and
 * <code>gcd(0, Integer.MIN_VALUE)</code> throw an
 * <code>ArithmeticException</code>, because the result would be 2^31, which
 * is too large for an int value.</li>
 * <li>The result of <code>gcd(x, x)</code>, <code>gcd(0, x)</code> and
 * <code>gcd(x, 0)</code> is the absolute value of <code>x</code>, except
 * for the special cases above.
 * <li>The invocation <code>gcd(0, 0)</code> is the only one which returns
 * <code>0</code>.</li>
 * </ul>
 *
 * @param p any number
 * @param q any number
 * @return the greatest common divisor, never negative
 * @throws ArithmeticException
 *             if the result cannot be represented as a nonnegative int
 *             value
 * @since 1.1
 */
public static int gcd(final int p, final int q) {
    int u = p;
    int v = q;
    if ((u == 0) || (v == 0)) {
        if ((u == Integer.MIN_VALUE) || (v == Integer.MIN_VALUE)) {
            throw MathRuntimeException.createArithmeticException(
                    "overflow: gcd({0}, {1}) is 2^31",
                    p, q);
        }
        return Math.abs(u) + Math.abs(v);
    }
    // keep u and v negative, as negative integers range down to
    // -2^31, while positive numbers can only be as large as 2^31-1
    // (i.e. we can't necessarily negate a negative number without
    // overflow)
    /* assert u!=0 && v!=0; */
    if (u > 0) {
        u = -u;
    } // make u negative
    if (v > 0) {
        v = -v;
    } // make v negative
    // B1. [Find power of 2]
    int k = 0;
    while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
                                                        // both even...
        u /= 2;
        v /= 2;
        k++; // cast out twos.
    }
    if (k == 31) {
        throw MathRuntimeException.createArithmeticException(
                "overflow: gcd({0}, {1}) is 2^31",
                p, q);
    }
    // B2. Initialize: u and v have been divided by 2^k and at least
    // one is odd.
    int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
    // t negative: u was odd, v may be even (t replaces v)
    // t positive: u was even, v is odd (t replaces u)
    do {
        /* assert u<0 && v<0; */
        // B4/B3: cast out twos from t.
        while ((t & 1) == 0) { // while t is even..
            t /= 2; // cast out twos
        }
        // B5 [reset max(u,v)]
        if (t > 0) {
            u = -t;
        } else {
            v = t;
        }
        // B6/B3. at this point both u and v should be odd.
        t = (v - u) / 2;
        // |u| larger: t positive (replace u)
        // |v| larger: t negative (replace v)
    } while (t != 0);
    return -u * (1 << k); // gcd is u*2^k
}
 
Example 16
Source File: Math_52_Rotation_s.java    From coming with MIT License 4 votes vote down vote up
/** Build a rotation from an axis and an angle.
 * <p>We use the convention that angles are oriented according to
 * the effect of the rotation on vectors around the axis. That means
 * that if (i, j, k) is a direct frame and if we first provide +k as
 * the axis and &pi;/2 as the angle to this constructor, and then
 * {@link #applyTo(Vector3D) apply} the instance to +i, we will get
 * +j.</p>
 * <p>Another way to represent our convention is to say that a rotation
 * of angle &theta; about the unit vector (x, y, z) is the same as the
 * rotation build from quaternion components { cos(-&theta;/2),
 * x * sin(-&theta;/2), y * sin(-&theta;/2), z * sin(-&theta;/2) }.
 * Note the minus sign on the angle!</p>
 * <p>On the one hand this convention is consistent with a vectorial
 * perspective (moving vectors in fixed frames), on the other hand it
 * is different from conventions with a frame perspective (fixed vectors
 * viewed from different frames) like the ones used for example in spacecraft
 * attitude community or in the graphics community.</p>
 * @param axis axis around which to rotate
 * @param angle rotation angle.
 * @exception ArithmeticException if the axis norm is zero
 */
public Rotation(Vector3D axis, double angle) {

  double norm = axis.getNorm();
  if (norm == 0) {
    throw MathRuntimeException.createArithmeticException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_AXIS);
  }

  double halfAngle = -0.5 * angle;
  double coeff = FastMath.sin(halfAngle) / norm;

  q0 = FastMath.cos (halfAngle);
  q1 = coeff * axis.getX();
  q2 = coeff * axis.getY();
  q3 = coeff * axis.getZ();

}
 
Example 17
Source File: MathUtils.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>
 * Gets the greatest common divisor of the absolute value of two numbers,
 * using the "binary gcd" method which avoids division and modulo
 * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
 * Stein (1961).
 * </p>
 * Special cases:
 * <ul>
 * <li>The invocations
 * <code>gcd(Long.MIN_VALUE, Long.MIN_VALUE)</code>,
 * <code>gcd(Long.MIN_VALUE, 0L)</code> and
 * <code>gcd(0L, Long.MIN_VALUE)</code> throw an
 * <code>ArithmeticException</code>, because the result would be 2^63, which
 * is too large for a long value.</li>
 * <li>The result of <code>gcd(x, x)</code>, <code>gcd(0L, x)</code> and
 * <code>gcd(x, 0L)</code> is the absolute value of <code>x</code>, except
 * for the special cases above.
 * <li>The invocation <code>gcd(0L, 0L)</code> is the only one which returns
 * <code>0L</code>.</li>
 * </ul>
 * 
 * @param p any number
 * @param q any number
 * @return the greatest common divisor, never negative
 * @throws ArithmeticException if the result cannot be represented as a nonnegative long
 * value
 * @since 2.1
 */
public static long gcd(final long p, final long q) {
    long u = p;
    long v = q;
    if ((u == 0) || (v == 0)) {
        if ((u == Long.MIN_VALUE) || (v == Long.MIN_VALUE)){
            throw MathRuntimeException.createArithmeticException(
                    "overflow: gcd({0}, {1}) is 2^63",
                    p, q);
        }
        return (Math.abs(u) + Math.abs(v));
    }
    // keep u and v negative, as negative integers range down to
    // -2^63, while positive numbers can only be as large as 2^63-1
    // (i.e. we can't necessarily negate a negative number without
    // overflow)
    /* assert u!=0 && v!=0; */
    if (u > 0) {
        u = -u;
    } // make u negative
    if (v > 0) {
        v = -v;
    } // make v negative
    // B1. [Find power of 2]
    int k = 0;
    while ((u & 1) == 0 && (v & 1) == 0 && k < 63) { // while u and v are
                                                        // both even...
        u /= 2;
        v /= 2;
        k++; // cast out twos.
    }
    if (k == 63) {
        throw MathRuntimeException.createArithmeticException(
                "overflow: gcd({0}, {1}) is 2^63",
                p, q);
    }
    // B2. Initialize: u and v have been divided by 2^k and at least
    // one is odd.
    long t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
    // t negative: u was odd, v may be even (t replaces v)
    // t positive: u was even, v is odd (t replaces u)
    do {
        /* assert u<0 && v<0; */
        // B4/B3: cast out twos from t.
        while ((t & 1) == 0) { // while t is even..
            t /= 2; // cast out twos
        }
        // B5 [reset max(u,v)]
        if (t > 0) {
            u = -t;
        } else {
            v = t;
        }
        // B6/B3. at this point both u and v should be odd.
        t = (v - u) / 2;
        // |u| larger: t positive (replace u)
        // |v| larger: t negative (replace v)
    } while (t != 0);
    return -u * (1L << k); // gcd is u*2^k
}
 
Example 18
Source File: BigFraction.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>
 * Divide the value of this fraction by the passed <code>BigInteger</code>,
 * ie "this * 1 / bg", returning the result in reduced form.
 * </p>
 *
 * @param bg
 *            the <code>BigInteger</code> to divide by, must not be
 *            <code>null</code>.
 * @return a {@link BigFraction} instance with the resulting values.
 * @throws NullArgumentException if the {@code BigInteger} is {@code null}.
 * @throws ArithmeticException
 *             if the fraction to divide by is zero.
 */
public BigFraction divide(final BigInteger bg) {
    if (BigInteger.ZERO.equals(bg)) {
        throw MathRuntimeException.createArithmeticException(LocalizedFormats.ZERO_DENOMINATOR);
    }
    return new BigFraction(numerator, denominator.multiply(bg));
}
 
Example 19
Source File: Cardumen_0053_t.java    From coming with MIT License 3 votes vote down vote up
/**
 * Add two integers, checking for overflow.
 *
 * @param x an addend
 * @param y an addend
 * @return the sum <code>x+y</code>
 * @throws ArithmeticException if the result can not be represented as an
 *         int
 * @since 1.1
 */
public static int addAndCheck(int x, int y) {
    long s = (long)x + (long)y;
    if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
        throw MathRuntimeException.createArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, x, y);
    }
    return (int)s;
}
 
Example 20
Source File: BigFraction.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>
 * Divide the value of this fraction by another, returning the result in
 * reduced form.
 * </p>
 * 
 * @param fraction
 *            the fraction to divide by, must not be <code>null</code>.
 * @return a {@link BigFraction} instance with the resulting values.
 * @throws NullPointerException
 *             if the fraction is <code>null</code>.
 * @throws ArithmeticException
 *             if the fraction to divide by is zero.
 */
public BigFraction divide(final BigFraction fraction) {
    if (BigInteger.ZERO.equals(fraction.numerator)) {
        throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
    }

    return multiply(fraction.reciprocal());
}