Added throw declarations for package util.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1381283 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Luc Maisonobe 2012-09-05 18:29:47 +00:00
parent 003f022df4
commit 1dd611f794
8 changed files with 158 additions and 86 deletions

View File

@ -61,7 +61,8 @@ public final class ArithmeticUtils {
* as an {@code int}. * as an {@code int}.
* @since 1.1 * @since 1.1
*/ */
public static int addAndCheck(int x, int y) { public static int addAndCheck(int x, int y)
throws MathArithmeticException {
long s = (long)x + (long)y; long s = (long)x + (long)y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, x, y); throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, x, y);
@ -79,7 +80,7 @@ public final class ArithmeticUtils {
* long * long
* @since 1.2 * @since 1.2
*/ */
public static long addAndCheck(long a, long b) { public static long addAndCheck(long a, long b) throws MathArithmeticException {
return ArithmeticUtils.addAndCheck(a, b, LocalizedFormats.OVERFLOW_IN_ADDITION); return ArithmeticUtils.addAndCheck(a, b, LocalizedFormats.OVERFLOW_IN_ADDITION);
} }
@ -109,7 +110,8 @@ public final class ArithmeticUtils {
* @throws MathArithmeticException if the result is too large to be * @throws MathArithmeticException if the result is too large to be
* represented by a long integer. * represented by a long integer.
*/ */
public static long binomialCoefficient(final int n, final int k) { public static long binomialCoefficient(final int n, final int k)
throws NotPositiveException, NumberIsTooLargeException, MathArithmeticException {
ArithmeticUtils.checkBinomial(n, k); ArithmeticUtils.checkBinomial(n, k);
if ((n == k) || (k == 0)) { if ((n == k) || (k == 0)) {
return 1; return 1;
@ -186,8 +188,11 @@ public final class ArithmeticUtils {
* @return {@code n choose k} * @return {@code n choose k}
* @throws NotPositiveException if {@code n < 0}. * @throws NotPositiveException if {@code n < 0}.
* @throws NumberIsTooLargeException if {@code k > n}. * @throws NumberIsTooLargeException if {@code k > n}.
* @throws MathArithmeticException if the result is too large to be
* represented by a long integer.
*/ */
public static double binomialCoefficientDouble(final int n, final int k) { public static double binomialCoefficientDouble(final int n, final int k)
throws NotPositiveException, NumberIsTooLargeException, MathArithmeticException {
ArithmeticUtils.checkBinomial(n, k); ArithmeticUtils.checkBinomial(n, k);
if ((n == k) || (k == 0)) { if ((n == k) || (k == 0)) {
return 1d; return 1d;
@ -228,8 +233,11 @@ public final class ArithmeticUtils {
* @return {@code n choose k} * @return {@code n choose k}
* @throws NotPositiveException if {@code n < 0}. * @throws NotPositiveException if {@code n < 0}.
* @throws NumberIsTooLargeException if {@code k > n}. * @throws NumberIsTooLargeException if {@code k > n}.
* @throws MathArithmeticException if the result is too large to be
* represented by a long integer.
*/ */
public static double binomialCoefficientLog(final int n, final int k) { public static double binomialCoefficientLog(final int n, final int k)
throws NotPositiveException, NumberIsTooLargeException, MathArithmeticException {
ArithmeticUtils.checkBinomial(n, k); ArithmeticUtils.checkBinomial(n, k);
if ((n == k) || (k == 0)) { if ((n == k) || (k == 0)) {
return 0; return 0;
@ -300,7 +308,7 @@ public final class ArithmeticUtils {
* @throws MathArithmeticException if {@code n > 20}: The factorial value is too * @throws MathArithmeticException if {@code n > 20}: The factorial value is too
* large to fit in a {@code long}. * large to fit in a {@code long}.
*/ */
public static long factorial(final int n) { public static long factorial(final int n) throws NotPositiveException, MathArithmeticException {
if (n < 0) { if (n < 0) {
throw new NotPositiveException(LocalizedFormats.FACTORIAL_NEGATIVE_PARAMETER, throw new NotPositiveException(LocalizedFormats.FACTORIAL_NEGATIVE_PARAMETER,
n); n);
@ -324,13 +332,13 @@ public final class ArithmeticUtils {
* @return {@code n!} * @return {@code n!}
* @throws NotPositiveException if {@code n < 0}. * @throws NotPositiveException if {@code n < 0}.
*/ */
public static double factorialDouble(final int n) { public static double factorialDouble(final int n) throws NotPositiveException, MathArithmeticException {
if (n < 0) { if (n < 0) {
throw new NotPositiveException(LocalizedFormats.FACTORIAL_NEGATIVE_PARAMETER, throw new NotPositiveException(LocalizedFormats.FACTORIAL_NEGATIVE_PARAMETER,
n); n);
} }
if (n < 21) { if (n < 21) {
return factorial(n); return FACTORIALS[n];
} }
return FastMath.floor(FastMath.exp(ArithmeticUtils.factorialLog(n)) + 0.5); return FastMath.floor(FastMath.exp(ArithmeticUtils.factorialLog(n)) + 0.5);
} }
@ -342,13 +350,13 @@ public final class ArithmeticUtils {
* @return {@code n!} * @return {@code n!}
* @throws NotPositiveException if {@code n < 0}. * @throws NotPositiveException if {@code n < 0}.
*/ */
public static double factorialLog(final int n) { public static double factorialLog(final int n) throws NotPositiveException {
if (n < 0) { if (n < 0) {
throw new NotPositiveException(LocalizedFormats.FACTORIAL_NEGATIVE_PARAMETER, throw new NotPositiveException(LocalizedFormats.FACTORIAL_NEGATIVE_PARAMETER,
n); n);
} }
if (n < 21) { if (n < 21) {
return FastMath.log(factorial(n)); return FastMath.log(FACTORIALS[n]);
} }
double logSum = 0; double logSum = 0;
for (int i = 2; i <= n; i++) { for (int i = 2; i <= n; i++) {
@ -529,7 +537,7 @@ public final class ArithmeticUtils {
* a non-negative {@code long} value. * a non-negative {@code long} value.
* @since 2.1 * @since 2.1
*/ */
public static long gcd(final long p, final long q) { public static long gcd(final long p, final long q) throws MathArithmeticException {
long u = p; long u = p;
long v = q; long v = q;
if ((u == 0) || (v == 0)) { if ((u == 0) || (v == 0)) {
@ -609,7 +617,7 @@ public final class ArithmeticUtils {
* a non-negative {@code int} value. * a non-negative {@code int} value.
* @since 1.1 * @since 1.1
*/ */
public static int lcm(int a, int b) { public static int lcm(int a, int b) throws MathArithmeticException {
if (a == 0 || b == 0){ if (a == 0 || b == 0){
return 0; return 0;
} }
@ -643,7 +651,7 @@ public final class ArithmeticUtils {
* as a non-negative {@code long} value. * as a non-negative {@code long} value.
* @since 2.1 * @since 2.1
*/ */
public static long lcm(long a, long b) { public static long lcm(long a, long b) throws MathArithmeticException {
if (a == 0 || b == 0){ if (a == 0 || b == 0){
return 0; return 0;
} }
@ -665,7 +673,7 @@ public final class ArithmeticUtils {
* represented as an {@code int}. * represented as an {@code int}.
* @since 1.1 * @since 1.1
*/ */
public static int mulAndCheck(int x, int y) { public static int mulAndCheck(int x, int y) throws MathArithmeticException {
long m = ((long)x) * ((long)y); long m = ((long)x) * ((long)y);
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) { if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
throw new MathArithmeticException(); throw new MathArithmeticException();
@ -683,7 +691,7 @@ public final class ArithmeticUtils {
* as a {@code long}. * as a {@code long}.
* @since 1.2 * @since 1.2
*/ */
public static long mulAndCheck(long a, long b) { public static long mulAndCheck(long a, long b) throws MathArithmeticException {
long ret; long ret;
if (a > b) { if (a > b) {
// use symmetry to reduce boundary cases // use symmetry to reduce boundary cases
@ -737,7 +745,7 @@ public final class ArithmeticUtils {
* as an {@code int}. * as an {@code int}.
* @since 1.1 * @since 1.1
*/ */
public static int subAndCheck(int x, int y) { public static int subAndCheck(int x, int y) throws MathArithmeticException {
long s = (long)x - (long)y; long s = (long)x - (long)y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_SUBTRACTION, x, y); throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_SUBTRACTION, x, y);
@ -755,7 +763,7 @@ public final class ArithmeticUtils {
* {@code long}. * {@code long}.
* @since 1.2 * @since 1.2
*/ */
public static long subAndCheck(long a, long b) { public static long subAndCheck(long a, long b) throws MathArithmeticException {
long ret; long ret;
if (b == Long.MIN_VALUE) { if (b == Long.MIN_VALUE) {
if (a < 0) { if (a < 0) {
@ -778,7 +786,7 @@ public final class ArithmeticUtils {
* @return k<sup>e</sup> * @return k<sup>e</sup>
* @throws NotPositiveException if {@code e < 0}. * @throws NotPositiveException if {@code e < 0}.
*/ */
public static int pow(final int k, int e) { public static int pow(final int k, int e) throws NotPositiveException {
if (e < 0) { if (e < 0) {
throw new NotPositiveException(LocalizedFormats.EXPONENT, e); throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
} }
@ -804,7 +812,7 @@ public final class ArithmeticUtils {
* @return k<sup>e</sup> * @return k<sup>e</sup>
* @throws NotPositiveException if {@code e < 0}. * @throws NotPositiveException if {@code e < 0}.
*/ */
public static int pow(final int k, long e) { public static int pow(final int k, long e) throws NotPositiveException {
if (e < 0) { if (e < 0) {
throw new NotPositiveException(LocalizedFormats.EXPONENT, e); throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
} }
@ -830,7 +838,7 @@ public final class ArithmeticUtils {
* @return k<sup>e</sup> * @return k<sup>e</sup>
* @throws NotPositiveException if {@code e < 0}. * @throws NotPositiveException if {@code e < 0}.
*/ */
public static long pow(final long k, int e) { public static long pow(final long k, int e) throws NotPositiveException {
if (e < 0) { if (e < 0) {
throw new NotPositiveException(LocalizedFormats.EXPONENT, e); throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
} }
@ -856,7 +864,7 @@ public final class ArithmeticUtils {
* @return k<sup>e</sup> * @return k<sup>e</sup>
* @throws NotPositiveException if {@code e < 0}. * @throws NotPositiveException if {@code e < 0}.
*/ */
public static long pow(final long k, long e) { public static long pow(final long k, long e) throws NotPositiveException {
if (e < 0) { if (e < 0) {
throw new NotPositiveException(LocalizedFormats.EXPONENT, e); throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
} }
@ -882,7 +890,7 @@ public final class ArithmeticUtils {
* @return k<sup>e</sup> * @return k<sup>e</sup>
* @throws NotPositiveException if {@code e < 0}. * @throws NotPositiveException if {@code e < 0}.
*/ */
public static BigInteger pow(final BigInteger k, int e) { public static BigInteger pow(final BigInteger k, int e) throws NotPositiveException {
if (e < 0) { if (e < 0) {
throw new NotPositiveException(LocalizedFormats.EXPONENT, e); throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
} }
@ -898,7 +906,7 @@ public final class ArithmeticUtils {
* @return k<sup>e</sup> * @return k<sup>e</sup>
* @throws NotPositiveException if {@code e < 0}. * @throws NotPositiveException if {@code e < 0}.
*/ */
public static BigInteger pow(final BigInteger k, long e) { public static BigInteger pow(final BigInteger k, long e) throws NotPositiveException {
if (e < 0) { if (e < 0) {
throw new NotPositiveException(LocalizedFormats.EXPONENT, e); throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
} }
@ -925,7 +933,7 @@ public final class ArithmeticUtils {
* @return k<sup>e</sup> * @return k<sup>e</sup>
* @throws NotPositiveException if {@code e < 0}. * @throws NotPositiveException if {@code e < 0}.
*/ */
public static BigInteger pow(final BigInteger k, BigInteger e) { public static BigInteger pow(final BigInteger k, BigInteger e) throws NotPositiveException {
if (e.compareTo(BigInteger.ZERO) < 0) { if (e.compareTo(BigInteger.ZERO) < 0) {
throw new NotPositiveException(LocalizedFormats.EXPONENT, e); throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
} }
@ -1039,7 +1047,7 @@ public final class ArithmeticUtils {
* as a {@code long}. * as a {@code long}.
* @since 1.2 * @since 1.2
*/ */
private static long addAndCheck(long a, long b, Localizable pattern) { private static long addAndCheck(long a, long b, Localizable pattern) throws MathArithmeticException {
long ret; long ret;
if (a > b) { if (a > b) {
// use symmetry to reduce boundary cases // use symmetry to reduce boundary cases
@ -1082,7 +1090,7 @@ public final class ArithmeticUtils {
* @throws NotPositiveException if {@code n < 0}. * @throws NotPositiveException if {@code n < 0}.
* @throws NumberIsTooLargeException if {@code k > n}. * @throws NumberIsTooLargeException if {@code k > n}.
*/ */
private static void checkBinomial(final int n, final int k) { private static void checkBinomial(final int n, final int k) throws NumberIsTooLargeException, NotPositiveException {
if (n < k) { if (n < k) {
throw new NumberIsTooLargeException(LocalizedFormats.BINOMIAL_INVALID_PARAMETERS_ORDER, throw new NumberIsTooLargeException(LocalizedFormats.BINOMIAL_INVALID_PARAMETERS_ORDER,
k, n, true); k, n, true);

View File

@ -248,7 +248,7 @@ public class BigReal implements FieldElement<BigReal>, Comparable<BigReal>, Seri
* *
* @throws MathArithmeticException if {@code a} is zero * @throws MathArithmeticException if {@code a} is zero
*/ */
public BigReal divide(BigReal a) { public BigReal divide(BigReal a) throws MathArithmeticException {
try { try {
return new BigReal(d.divide(a.d, scale, roundingMode)); return new BigReal(d.divide(a.d, scale, roundingMode));
} catch (ArithmeticException e) { } catch (ArithmeticException e) {
@ -262,7 +262,7 @@ public class BigReal implements FieldElement<BigReal>, Comparable<BigReal>, Seri
* *
* @throws MathArithmeticException if {@code this} is zero * @throws MathArithmeticException if {@code this} is zero
*/ */
public BigReal reciprocal() { public BigReal reciprocal() throws MathArithmeticException {
try { try {
return new BigReal(BigDecimal.ONE.divide(d, scale, roundingMode)); return new BigReal(BigDecimal.ONE.divide(d, scale, roundingMode));
} catch (ArithmeticException e) { } catch (ArithmeticException e) {

View File

@ -17,6 +17,7 @@
package org.apache.commons.math3.util; package org.apache.commons.math3.util;
import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.ConvergenceException;
import org.apache.commons.math3.exception.MathInternalError;
import org.apache.commons.math3.exception.MaxCountExceededException; import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.util.LocalizedFormats;
@ -69,8 +70,13 @@ public abstract class ContinuedFraction {
* @return the value of the continued fraction evaluated at x. * @return the value of the continued fraction evaluated at x.
* @throws ConvergenceException if the algorithm fails to converge. * @throws ConvergenceException if the algorithm fails to converge.
*/ */
public double evaluate(double x) { public double evaluate(double x) throws ConvergenceException {
try {
return evaluate(x, DEFAULT_EPSILON, Integer.MAX_VALUE); return evaluate(x, DEFAULT_EPSILON, Integer.MAX_VALUE);
} catch (MaxCountExceededException e) {
// this should never happen as integers never exceed MAX_VALUE
throw new MathInternalError(e);
}
} }
/** /**
@ -80,8 +86,13 @@ public abstract class ContinuedFraction {
* @return the value of the continued fraction evaluated at x. * @return the value of the continued fraction evaluated at x.
* @throws ConvergenceException if the algorithm fails to converge. * @throws ConvergenceException if the algorithm fails to converge.
*/ */
public double evaluate(double x, double epsilon) { public double evaluate(double x, double epsilon) throws ConvergenceException {
try {
return evaluate(x, epsilon, Integer.MAX_VALUE); return evaluate(x, epsilon, Integer.MAX_VALUE);
} catch (MaxCountExceededException e) {
// this should never happen as integers never exceed MAX_VALUE
throw new MathInternalError(e);
}
} }
/** /**
@ -90,8 +101,10 @@ public abstract class ContinuedFraction {
* @param maxIterations maximum number of convergents * @param maxIterations maximum number of convergents
* @return the value of the continued fraction evaluated at x. * @return the value of the continued fraction evaluated at x.
* @throws ConvergenceException if the algorithm fails to converge. * @throws ConvergenceException if the algorithm fails to converge.
* @throws MaxCountExceededException if maximal number of iterations is reached
*/ */
public double evaluate(double x, int maxIterations) { public double evaluate(double x, int maxIterations)
throws ConvergenceException, MaxCountExceededException {
return evaluate(x, DEFAULT_EPSILON, maxIterations); return evaluate(x, DEFAULT_EPSILON, maxIterations);
} }
@ -119,8 +132,10 @@ public abstract class ContinuedFraction {
* @param maxIterations maximum number of convergents * @param maxIterations maximum number of convergents
* @return the value of the continued fraction evaluated at x. * @return the value of the continued fraction evaluated at x.
* @throws ConvergenceException if the algorithm fails to converge. * @throws ConvergenceException if the algorithm fails to converge.
* @throws MaxCountExceededException if maximal number of iterations is reached
*/ */
public double evaluate(double x, double epsilon, int maxIterations) { public double evaluate(double x, double epsilon, int maxIterations)
throws ConvergenceException, MaxCountExceededException {
final double small = 1e-50; final double small = 1e-50;
double hPrev = getA(0, x); double hPrev = getA(0, x);

View File

@ -209,7 +209,12 @@ public class MathArrays {
public static boolean isMonotonic(double[] val, public static boolean isMonotonic(double[] val,
OrderDirection dir, OrderDirection dir,
boolean strict) { boolean strict) {
try {
return checkOrder(val, dir, strict, false); return checkOrder(val, dir, strict, false);
} catch (NonMonotonicSequenceException e) {
// this should never happen as abort is set to false
throw new MathInternalError(e);
}
} }
/** /**
@ -224,7 +229,8 @@ public class MathArrays {
* and {@code abort} is {@code true}. * and {@code abort} is {@code true}.
*/ */
public static boolean checkOrder(double[] val, OrderDirection dir, public static boolean checkOrder(double[] val, OrderDirection dir,
boolean strict, boolean abort) { boolean strict, boolean abort)
throws NonMonotonicSequenceException {
double previous = val[0]; double previous = val[0];
final int max = val.length; final int max = val.length;
@ -285,7 +291,7 @@ public class MathArrays {
* @since 2.2 * @since 2.2
*/ */
public static void checkOrder(double[] val, OrderDirection dir, public static void checkOrder(double[] val, OrderDirection dir,
boolean strict) { boolean strict) throws NonMonotonicSequenceException {
checkOrder(val, dir, strict, true); checkOrder(val, dir, strict, true);
} }
@ -296,7 +302,7 @@ public class MathArrays {
* @throws NonMonotonicSequenceException if the array is not sorted. * @throws NonMonotonicSequenceException if the array is not sorted.
* @since 2.2 * @since 2.2
*/ */
public static void checkOrder(double[] val) { public static void checkOrder(double[] val) throws NonMonotonicSequenceException {
checkOrder(val, OrderDirection.INCREASING, true); checkOrder(val, OrderDirection.INCREASING, true);
} }
@ -431,8 +437,8 @@ public class MathArrays {
* @throws NullArgumentException if {@code x} or any {@code y} is null. * @throws NullArgumentException if {@code x} or any {@code y} is null.
* @since 3.0 * @since 3.0
*/ */
public static void sortInPlace(double[] x, public static void sortInPlace(double[] x, double[] ... yList)
double[] ... yList) { throws DimensionMismatchException, NullArgumentException {
sortInPlace(x, OrderDirection.INCREASING, yList); sortInPlace(x, OrderDirection.INCREASING, yList);
} }
@ -455,7 +461,8 @@ public class MathArrays {
*/ */
public static void sortInPlace(double[] x, public static void sortInPlace(double[] x,
final OrderDirection dir, final OrderDirection dir,
double[] ... yList) { double[] ... yList)
throws NullArgumentException, DimensionMismatchException {
if (x == null) { if (x == null) {
throw new NullArgumentException(); throw new NullArgumentException();
} }
@ -577,8 +584,10 @@ public class MathArrays {
* @param a Factors. * @param a Factors.
* @param b Factors. * @param b Factors.
* @return <code>&Sigma;<sub>i</sub> a<sub>i</sub> b<sub>i</sub></code>. * @return <code>&Sigma;<sub>i</sub> a<sub>i</sub> b<sub>i</sub></code>.
* @throws DimensionMismatchException if arrays dimensions don't match
*/ */
public static double linearCombination(final double[] a, final double[] b) { public static double linearCombination(final double[] a, final double[] b)
throws DimensionMismatchException {
final int len = a.length; final int len = a.length;
if (len != b.length) { if (len != b.length) {
throw new DimensionMismatchException(len, b.length); throw new DimensionMismatchException(len, b.length);
@ -1052,7 +1061,8 @@ public class MathArrays {
* @throws MathIllegalArgumentException if the target sum is infinite or {@code NaN}. * @throws MathIllegalArgumentException if the target sum is infinite or {@code NaN}.
* @since 2.1 * @since 2.1
*/ */
public static double[] normalizeArray(double[] values, double normalizedSum) { public static double[] normalizeArray(double[] values, double normalizedSum)
throws MathIllegalArgumentException, MathArithmeticException {
if (Double.isInfinite(normalizedSum)) { if (Double.isInfinite(normalizedSum)) {
throw new MathIllegalArgumentException(LocalizedFormats.NORMALIZE_INFINITE); throw new MathIllegalArgumentException(LocalizedFormats.NORMALIZE_INFINITE);
} }

View File

@ -124,7 +124,8 @@ public final class MathUtils {
* @throws MathArithmeticException if {@code magnitude == Byte.MIN_VALUE} * @throws MathArithmeticException if {@code magnitude == Byte.MIN_VALUE}
* and {@code sign >= 0}. * and {@code sign >= 0}.
*/ */
public static byte copySign(byte magnitude, byte sign) { public static byte copySign(byte magnitude, byte sign)
throws MathArithmeticException {
if ((magnitude >= 0 && sign >= 0) || if ((magnitude >= 0 && sign >= 0) ||
(magnitude < 0 && sign < 0)) { // Sign is OK. (magnitude < 0 && sign < 0)) { // Sign is OK.
return magnitude; return magnitude;
@ -146,7 +147,8 @@ public final class MathUtils {
* @throws MathArithmeticException if {@code magnitude == Short.MIN_VALUE} * @throws MathArithmeticException if {@code magnitude == Short.MIN_VALUE}
* and {@code sign >= 0}. * and {@code sign >= 0}.
*/ */
public static short copySign(short magnitude, short sign) { public static short copySign(short magnitude, short sign)
throws MathArithmeticException {
if ((magnitude >= 0 && sign >= 0) || if ((magnitude >= 0 && sign >= 0) ||
(magnitude < 0 && sign < 0)) { // Sign is OK. (magnitude < 0 && sign < 0)) { // Sign is OK.
return magnitude; return magnitude;
@ -168,7 +170,8 @@ public final class MathUtils {
* @throws MathArithmeticException if {@code magnitude == Integer.MIN_VALUE} * @throws MathArithmeticException if {@code magnitude == Integer.MIN_VALUE}
* and {@code sign >= 0}. * and {@code sign >= 0}.
*/ */
public static int copySign(int magnitude, int sign) { public static int copySign(int magnitude, int sign)
throws MathArithmeticException {
if ((magnitude >= 0 && sign >= 0) || if ((magnitude >= 0 && sign >= 0) ||
(magnitude < 0 && sign < 0)) { // Sign is OK. (magnitude < 0 && sign < 0)) { // Sign is OK.
return magnitude; return magnitude;
@ -190,7 +193,8 @@ public final class MathUtils {
* @throws MathArithmeticException if {@code magnitude == Long.MIN_VALUE} * @throws MathArithmeticException if {@code magnitude == Long.MIN_VALUE}
* and {@code sign >= 0}. * and {@code sign >= 0}.
*/ */
public static long copySign(long magnitude, long sign) { public static long copySign(long magnitude, long sign)
throws MathArithmeticException {
if ((magnitude >= 0 && sign >= 0) || if ((magnitude >= 0 && sign >= 0) ||
(magnitude < 0 && sign < 0)) { // Sign is OK. (magnitude < 0 && sign < 0)) { // Sign is OK.
return magnitude; return magnitude;
@ -208,7 +212,8 @@ public final class MathUtils {
* @throws NotFiniteNumberException if {@code x} is not a * @throws NotFiniteNumberException if {@code x} is not a
* finite real number. * finite real number.
*/ */
public static void checkFinite(final double x) { public static void checkFinite(final double x)
throws NotFiniteNumberException {
if (Double.isInfinite(x) || Double.isNaN(x)) { if (Double.isInfinite(x) || Double.isNaN(x)) {
throw new NotFiniteNumberException(x); throw new NotFiniteNumberException(x);
} }
@ -221,7 +226,8 @@ public final class MathUtils {
* @throws NotFiniteNumberException if any values of the array is not a * @throws NotFiniteNumberException if any values of the array is not a
* finite real number. * finite real number.
*/ */
public static void checkFinite(final double[] val) { public static void checkFinite(final double[] val)
throws NotFiniteNumberException {
for (int i = 0; i < val.length; i++) { for (int i = 0; i < val.length; i++) {
final double x = val[i]; final double x = val[i];
if (Double.isInfinite(x) || Double.isNaN(x)) { if (Double.isInfinite(x) || Double.isNaN(x)) {
@ -240,7 +246,8 @@ public final class MathUtils {
*/ */
public static void checkNotNull(Object o, public static void checkNotNull(Object o,
Localizable pattern, Localizable pattern,
Object ... args) { Object ... args)
throws NullArgumentException {
if (o == null) { if (o == null) {
throw new NullArgumentException(pattern, args); throw new NullArgumentException(pattern, args);
} }

View File

@ -18,6 +18,7 @@
package org.apache.commons.math3.util; package org.apache.commons.math3.util;
import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MathInternalError;
import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException;
@ -162,7 +163,7 @@ public class MultidimensionalCounter implements Iterable<Integer> {
* @throws NotStrictlyPositiveException if one of the sizes is * @throws NotStrictlyPositiveException if one of the sizes is
* negative or zero. * negative or zero.
*/ */
public MultidimensionalCounter(int ... size) { public MultidimensionalCounter(int ... size) throws NotStrictlyPositiveException {
dimension = size.length; dimension = size.length;
this.size = MathArrays.copyOf(size); this.size = MathArrays.copyOf(size);
@ -213,7 +214,7 @@ public class MultidimensionalCounter implements Iterable<Integer> {
* @throws OutOfRangeException if {@code index} is not between * @throws OutOfRangeException if {@code index} is not between
* {@code 0} and the value returned by {@link #getSize()} (excluded). * {@code 0} and the value returned by {@link #getSize()} (excluded).
*/ */
public int[] getCounts(int index) { public int[] getCounts(int index) throws OutOfRangeException {
if (index < 0 || if (index < 0 ||
index >= totalSize) { index >= totalSize) {
throw new OutOfRangeException(index, 0, totalSize); throw new OutOfRangeException(index, 0, totalSize);
@ -250,7 +251,8 @@ public class MultidimensionalCounter implements Iterable<Integer> {
* the range of the corresponding dimension, as defined in the * the range of the corresponding dimension, as defined in the
* {@link MultidimensionalCounter#MultidimensionalCounter(int...) constructor}. * {@link MultidimensionalCounter#MultidimensionalCounter(int...) constructor}.
*/ */
public int getCount(int ... c) throws OutOfRangeException { public int getCount(int ... c)
throws OutOfRangeException, DimensionMismatchException {
if (c.length != dimension) { if (c.length != dimension) {
throw new DimensionMismatchException(c.length, dimension); throw new DimensionMismatchException(c.length, dimension);
} }
@ -290,7 +292,15 @@ public class MultidimensionalCounter implements Iterable<Integer> {
public String toString() { public String toString() {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (int i = 0; i < dimension; i++) { for (int i = 0; i < dimension; i++) {
try {
sb.append("[").append(getCount(i)).append("]"); sb.append("[").append(getCount(i)).append("]");
} catch (OutOfRangeException e) {
// this should never happen
throw new MathInternalError(e);
} catch (DimensionMismatchException e) {
// this should never happen
throw new MathInternalError(e);
}
} }
return sb.toString(); return sb.toString();
} }

View File

@ -20,6 +20,7 @@ package org.apache.commons.math3.util;
import java.math.BigDecimal; import java.math.BigDecimal;
import org.apache.commons.math3.exception.MathArithmeticException; import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.exception.MathInternalError;
import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.util.LocalizedFormats;
/** /**
@ -391,7 +392,15 @@ public class Precision {
* @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0) * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
*/ */
public static float round(float x, int scale) { public static float round(float x, int scale) {
try {
return round(x, scale, BigDecimal.ROUND_HALF_UP); return round(x, scale, BigDecimal.ROUND_HALF_UP);
} catch (MathArithmeticException e) {
// should never happen as we don't use BigDecimal.ROUND_UNNECESSARY
throw new MathInternalError(e);
} catch (MathIllegalArgumentException e) {
// should never happen as we use a valid rounding
throw new MathInternalError(e);
}
} }
/** /**
@ -404,8 +413,11 @@ public class Precision {
* @param roundingMethod Rounding method as defined in {@link BigDecimal}. * @param roundingMethod Rounding method as defined in {@link BigDecimal}.
* @return the rounded value. * @return the rounded value.
* @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0) * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
* @throws MathArithmeticException if an exact operation is required but result is not exact
* @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method.
*/ */
public static float round(float x, int scale, int roundingMethod) { public static float round(float x, int scale, int roundingMethod)
throws MathArithmeticException, MathIllegalArgumentException {
final float sign = FastMath.copySign(1f, x); final float sign = FastMath.copySign(1f, x);
final float factor = (float) FastMath.pow(10.0f, scale) * sign; final float factor = (float) FastMath.pow(10.0f, scale) * sign;
return (float) roundUnscaled(x * factor, sign, roundingMethod) / factor; return (float) roundUnscaled(x * factor, sign, roundingMethod) / factor;
@ -420,12 +432,14 @@ public class Precision {
* @param sign Sign of the original, scaled value. * @param sign Sign of the original, scaled value.
* @param roundingMethod Rounding method, as defined in {@link BigDecimal}. * @param roundingMethod Rounding method, as defined in {@link BigDecimal}.
* @return the rounded value. * @return the rounded value.
* @throws MathArithmeticException if an exact operation is required but result is not exact
* @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method. * @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method.
* @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0) * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
*/ */
private static double roundUnscaled(double unscaled, private static double roundUnscaled(double unscaled,
double sign, double sign,
int roundingMethod) { int roundingMethod)
throws MathArithmeticException, MathIllegalArgumentException {
switch (roundingMethod) { switch (roundingMethod) {
case BigDecimal.ROUND_CEILING : case BigDecimal.ROUND_CEILING :
if (sign == -1) { if (sign == -1) {

View File

@ -21,6 +21,7 @@ import java.util.Arrays;
import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.MathIllegalStateException;
import org.apache.commons.math3.exception.MathInternalError;
import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.util.LocalizedFormats;
@ -155,9 +156,9 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* <li><code>contractionFactor = 2.0</code></li> * <li><code>contractionFactor = 2.0</code></li>
* </ul> * </ul>
* @param initialCapacity The initial size of the internal storage array * @param initialCapacity The initial size of the internal storage array
* @throws IllegalArgumentException if initialCapacity is not > 0 * @throws MathIllegalArgumentException if initialCapacity is not > 0
*/ */
public ResizableDoubleArray(int initialCapacity) { public ResizableDoubleArray(int initialCapacity) throws MathIllegalArgumentException {
setInitialCapacity(initialCapacity); setInitialCapacity(initialCapacity);
internalArray = new double[this.initialCapacity]; internalArray = new double[this.initialCapacity];
} }
@ -210,9 +211,9 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* @param initialCapacity The initial size of the internal storage array * @param initialCapacity The initial size of the internal storage array
* @param expansionFactor the array will be expanded based on this * @param expansionFactor the array will be expanded based on this
* parameter * parameter
* @throws IllegalArgumentException if parameters are not valid * @throws MathIllegalArgumentException if parameters are not valid
*/ */
public ResizableDoubleArray(int initialCapacity, float expansionFactor) { public ResizableDoubleArray(int initialCapacity, float expansionFactor) throws MathIllegalArgumentException {
this.expansionFactor = expansionFactor; this.expansionFactor = expansionFactor;
setInitialCapacity(initialCapacity); setInitialCapacity(initialCapacity);
internalArray = new double[initialCapacity]; internalArray = new double[initialCapacity];
@ -236,10 +237,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* @param expansionFactor the array will be expanded based on this * @param expansionFactor the array will be expanded based on this
* parameter * parameter
* @param contractionCriteria The contraction Criteria. * @param contractionCriteria The contraction Criteria.
* @throws IllegalArgumentException if parameters are not valid * @throws MathIllegalArgumentException if parameters are not valid
*/ */
public ResizableDoubleArray(int initialCapacity, float expansionFactor, public ResizableDoubleArray(int initialCapacity, float expansionFactor,
float contractionCriteria) { float contractionCriteria) throws MathIllegalArgumentException {
this.expansionFactor = expansionFactor; this.expansionFactor = expansionFactor;
setContractionCriteria(contractionCriteria); setContractionCriteria(contractionCriteria);
setInitialCapacity(initialCapacity); setInitialCapacity(initialCapacity);
@ -265,10 +266,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* parameter * parameter
* @param contractionCriteria the contraction Criteria * @param contractionCriteria the contraction Criteria
* @param expansionMode the expansion mode * @param expansionMode the expansion mode
* @throws IllegalArgumentException if parameters are not valid * @throws MathIllegalArgumentException if parameters are not valid
*/ */
public ResizableDoubleArray(int initialCapacity, float expansionFactor, public ResizableDoubleArray(int initialCapacity, float expansionFactor,
float contractionCriteria, int expansionMode) { float contractionCriteria, int expansionMode) throws MathIllegalArgumentException {
this.expansionFactor = expansionFactor; this.expansionFactor = expansionFactor;
setContractionCriteria(contractionCriteria); setContractionCriteria(contractionCriteria);
setInitialCapacity(initialCapacity); setInitialCapacity(initialCapacity);
@ -365,10 +366,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* *
* @param value new value to substitute for the most recently added value * @param value new value to substitute for the most recently added value
* @return value that has been replaced in the array * @return value that has been replaced in the array
* @throws IllegalStateException if the array is empty * @throws MathIllegalStateException if the array is empty
* @since 2.0 * @since 2.0
*/ */
public synchronized double substituteMostRecentElement(double value) { public synchronized double substituteMostRecentElement(double value) throws MathIllegalStateException {
if (numElements < 1) { if (numElements < 1) {
throw new MathIllegalStateException( throw new MathIllegalStateException(
LocalizedFormats.CANNOT_SUBSTITUTE_ELEMENT_FROM_EMPTY_ARRAY); LocalizedFormats.CANNOT_SUBSTITUTE_ELEMENT_FROM_EMPTY_ARRAY);
@ -389,10 +390,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* *
* @param expansion factor to be checked * @param expansion factor to be checked
* @param contraction criteria to be checked * @param contraction criteria to be checked
* @throws IllegalArgumentException if the contractionCriteria is less than * @throws MathIllegalArgumentException if the contractionCriteria is less than
* the expansionCriteria. * the expansionCriteria.
*/ */
protected void checkContractExpand(float contraction, float expansion) { protected void checkContractExpand(float contraction, float expansion) throws MathIllegalArgumentException {
if (contraction < expansion) { if (contraction < expansion) {
throw new MathIllegalArgumentException( throw new MathIllegalArgumentException(
@ -447,10 +448,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* if i exceeds numElements. * if i exceeds numElements.
* *
* @param i the number of elements to discard from the front of the array * @param i the number of elements to discard from the front of the array
* @throws IllegalArgumentException if i is greater than numElements. * @throws MathIllegalArgumentException if i is greater than numElements.
* @since 2.0 * @since 2.0
*/ */
public synchronized void discardFrontElements(int i) { public synchronized void discardFrontElements(int i) throws MathIllegalArgumentException {
discardExtremeElements(i,true); discardExtremeElements(i,true);
@ -464,10 +465,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* if i exceeds numElements. * if i exceeds numElements.
* *
* @param i the number of elements to discard from the end of the array * @param i the number of elements to discard from the end of the array
* @throws IllegalArgumentException if i is greater than numElements. * @throws MathIllegalArgumentException if i is greater than numElements.
* @since 2.0 * @since 2.0
*/ */
public synchronized void discardMostRecentElements(int i) { public synchronized void discardMostRecentElements(int i) throws MathIllegalArgumentException {
discardExtremeElements(i,false); discardExtremeElements(i,false);
@ -489,10 +490,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* @param front true if elements are to be discarded from the front * @param front true if elements are to be discarded from the front
* of the array, false if elements are to be discarded from the end * of the array, false if elements are to be discarded from the end
* of the array * of the array
* @throws IllegalArgumentException if i is greater than numElements. * @throws MathIllegalArgumentException if i is greater than numElements.
* @since 2.0 * @since 2.0
*/ */
private synchronized void discardExtremeElements(int i,boolean front) { private synchronized void discardExtremeElements(int i,boolean front) throws MathIllegalArgumentException {
if (i > numElements) { if (i > numElements) {
throw new MathIllegalArgumentException( throw new MathIllegalArgumentException(
LocalizedFormats.TOO_MANY_ELEMENTS_TO_DISCARD_FROM_ARRAY, LocalizedFormats.TOO_MANY_ELEMENTS_TO_DISCARD_FROM_ARRAY,
@ -671,8 +672,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* Sets the contraction criteria for this ExpandContractDoubleArray. * Sets the contraction criteria for this ExpandContractDoubleArray.
* *
* @param contractionCriteria contraction criteria * @param contractionCriteria contraction criteria
* @throws MathIllegalArgumentException if the contractionCriteria is less than
* the expansionCriteria.
*/ */
public void setContractionCriteria(float contractionCriteria) { public void setContractionCriteria(float contractionCriteria) throws MathIllegalArgumentException {
checkContractExpand(contractionCriteria, getExpansionFactor()); checkContractExpand(contractionCriteria, getExpansionFactor());
synchronized(this) { synchronized(this) {
this.contractionCriteria = contractionCriteria; this.contractionCriteria = contractionCriteria;
@ -713,10 +716,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* <li><code>contractionFactor >= expansionFactor</code></li> * <li><code>contractionFactor >= expansionFactor</code></li>
* </ul> * </ul>
* @param expansionFactor the new expansion factor value. * @param expansionFactor the new expansion factor value.
* @throws IllegalArgumentException if expansionFactor is <= 1 or greater * @throws MathIllegalArgumentException if expansionFactor is <= 1 or greater
* than contractionFactor * than contractionFactor
*/ */
public void setExpansionFactor(float expansionFactor) { public void setExpansionFactor(float expansionFactor) throws MathIllegalArgumentException {
checkContractExpand(getContractionCriteria(), expansionFactor); checkContractExpand(getContractionCriteria(), expansionFactor);
// The check above verifies that the expansion factor is > 1.0; // The check above verifies that the expansion factor is > 1.0;
synchronized(this) { synchronized(this) {
@ -729,9 +732,9 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* ADDITIVE_MODE, MULTIPLICATIVE_MODE. * ADDITIVE_MODE, MULTIPLICATIVE_MODE.
* *
* @param expansionMode The expansionMode to set. * @param expansionMode The expansionMode to set.
* @throws IllegalArgumentException if the specified mode value is not valid * @throws MathIllegalArgumentException if the specified mode value is not valid
*/ */
public void setExpansionMode(int expansionMode) { public void setExpansionMode(int expansionMode) throws MathIllegalArgumentException {
if (expansionMode != MULTIPLICATIVE_MODE && if (expansionMode != MULTIPLICATIVE_MODE &&
expansionMode != ADDITIVE_MODE) { expansionMode != ADDITIVE_MODE) {
throw new MathIllegalArgumentException( throw new MathIllegalArgumentException(
@ -748,10 +751,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* Sets the initial capacity. Should only be invoked by constructors. * Sets the initial capacity. Should only be invoked by constructors.
* *
* @param initialCapacity of the array * @param initialCapacity of the array
* @throws IllegalArgumentException if <code>initialCapacity</code> is not * @throws MathIllegalArgumentException if <code>initialCapacity</code> is not
* positive. * positive.
*/ */
protected void setInitialCapacity(int initialCapacity) { protected void setInitialCapacity(int initialCapacity) throws MathIllegalArgumentException {
if (initialCapacity > 0) { if (initialCapacity > 0) {
synchronized(this) { synchronized(this) {
this.initialCapacity = initialCapacity; this.initialCapacity = initialCapacity;
@ -769,9 +772,9 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* array. This function will also expand the internal array as needed. * array. This function will also expand the internal array as needed.
* *
* @param i a new number of elements * @param i a new number of elements
* @throws IllegalArgumentException if <code>i</code> is negative. * @throws MathIllegalArgumentException if <code>i</code> is negative.
*/ */
public synchronized void setNumElements(int i) { public synchronized void setNumElements(int i) throws MathIllegalArgumentException {
// If index is negative thrown an error // If index is negative thrown an error
if (i < 0) { if (i < 0) {
@ -862,9 +865,14 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
* @since 2.0 * @since 2.0
*/ */
public synchronized ResizableDoubleArray copy() { public synchronized ResizableDoubleArray copy() {
try {
ResizableDoubleArray result = new ResizableDoubleArray(); ResizableDoubleArray result = new ResizableDoubleArray();
copy(this, result); copy(this, result);
return result; return result;
} catch (NullArgumentException e) {
// this should never happen
throw new MathInternalError(e);
}
} }
/** /**