diff --git a/checkstyle.xml b/checkstyle.xml index e9683534e..58bcb7e70 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -90,6 +90,14 @@ + + + + + + + + Generic univariate summary statistic objects. - +

UnivariateStatistic API Usage Examples:

UnivariateStatistic:

/* evaluation approach */
double[] values = new double[] { 1, 2, @@ -28,7 +28,7 @@

StorelessUnivariateStatistic:

/* incremental approach */
double[] values = new double[] { 1, 2, 3, 4, 5 };
- StorelessUnivariateStatistic stat = new Mean();
+ StorelessUnivariateStatistic stat = new Mean();
System.out.println("mean before adding a value is NaN = " + stat.getResult());
for (int i = 0; i < values.length; i++) {
    *
    - *
  • The result is NaN iff all values are NaN + *
  • The result is NaN iff all values are NaN * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.POSITIVE_INFINITY, + *
  • If any of the values equals Double.POSITIVE_INFINITY, * the result is Double.POSITIVE_INFINITY.
  • *

*

- * Note that this implementation is not synchronized. If + * Note that this implementation is not synchronized. If * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or + * one of the threads invokes the increment() or * clear() method, it must be synchronized externally.

- * + * * @version $Revision$ $Date$ */ public class Max extends AbstractStorelessUnivariateStatistic implements Serializable { /** Serializable version identifier */ - private static final long serialVersionUID = -5593383832225844641L; - + private static final long serialVersionUID = -5593383832225844641L; + /** Number of values that have been added */ private long n; - + /** Current value of the statistic */ private double value; @@ -55,17 +55,17 @@ public class Max extends AbstractStorelessUnivariateStatistic implements Seriali n = 0; value = Double.NaN; } - + /** * Copy constructor, creates a new {@code Max} identical * to the {@code original} - * + * * @param original the {@code Max} instance to copy */ public Max(Max original) { copy(original, this); } - + /** * {@inheritDoc} */ @@ -100,7 +100,7 @@ public class Max extends AbstractStorelessUnivariateStatistic implements Seriali public long getN() { return n; } - + /** * Returns the maximum of the entries in the specified portion of * the input array, or Double.NaN if the designated subarray @@ -110,12 +110,12 @@ public class Max extends AbstractStorelessUnivariateStatistic implements Seriali * the array index parameters are not valid.

*

*

    - *
  • The result is NaN iff all values are NaN + *
  • The result is NaN iff all values are NaN * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.POSITIVE_INFINITY, + *
  • If any of the values equals Double.POSITIVE_INFINITY, * the result is Double.POSITIVE_INFINITY.
  • *

- * + * * @param values the input array * @param begin index of the first array element to include * @param length the number of elements to include @@ -136,7 +136,7 @@ public class Max extends AbstractStorelessUnivariateStatistic implements Seriali } return max; } - + /** * {@inheritDoc} */ @@ -146,11 +146,11 @@ public class Max extends AbstractStorelessUnivariateStatistic implements Seriali copy(this, result); return result; } - + /** * Copies source to dest. *

Neither source nor dest can be null.

- * + * * @param source Max to copy * @param dest Max to copy to * @throws NullPointerException if either source or dest is null diff --git a/src/main/java/org/apache/commons/math/stat/descriptive/rank/Median.java b/src/main/java/org/apache/commons/math/stat/descriptive/rank/Median.java index 49f8046f8..2d4336f40 100644 --- a/src/main/java/org/apache/commons/math/stat/descriptive/rank/Median.java +++ b/src/main/java/org/apache/commons/math/stat/descriptive/rank/Median.java @@ -23,17 +23,17 @@ import java.io.Serializable; * Returns the median of the available values. This is the same as the 50th percentile. * See {@link Percentile} for a description of the algorithm used. *

- * Note that this implementation is not synchronized. If + * Note that this implementation is not synchronized. If * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or + * one of the threads invokes the increment() or * clear() method, it must be synchronized externally.

- * + * * @version $Revision$ $Date$ */ public class Median extends Percentile implements Serializable { /** Serializable version identifier */ - private static final long serialVersionUID = -3961477041290915687L; + private static final long serialVersionUID = -3961477041290915687L; /** * Default constructor. @@ -41,15 +41,15 @@ public class Median extends Percentile implements Serializable { public Median() { super(50.0); } - + /** * Copy constructor, creates a new {@code Median} identical * to the {@code original} - * + * * @param original the {@code Median} instance to copy */ public Median(Median original) { super(original); - } + } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/math/stat/descriptive/rank/Min.java b/src/main/java/org/apache/commons/math/stat/descriptive/rank/Min.java index 8eb44ec70..c01984bc4 100644 --- a/src/main/java/org/apache/commons/math/stat/descriptive/rank/Min.java +++ b/src/main/java/org/apache/commons/math/stat/descriptive/rank/Min.java @@ -24,27 +24,27 @@ import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStati * Returns the minimum of the available values. *

*

    - *
  • The result is NaN iff all values are NaN + *
  • The result is NaN iff all values are NaN * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.NEGATIVE_INFINITY, + *
  • If any of the values equals Double.NEGATIVE_INFINITY, * the result is Double.NEGATIVE_INFINITY.
  • *

*

- * Note that this implementation is not synchronized. If + * Note that this implementation is not synchronized. If * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or + * one of the threads invokes the increment() or * clear() method, it must be synchronized externally.

- * + * * @version $Revision$ $Date$ */ public class Min extends AbstractStorelessUnivariateStatistic implements Serializable { /** Serializable version identifier */ - private static final long serialVersionUID = -2941995784909003131L; - + private static final long serialVersionUID = -2941995784909003131L; + /**Number of values that have been added */ private long n; - + /**Current value of the statistic */ private double value; @@ -55,17 +55,17 @@ public class Min extends AbstractStorelessUnivariateStatistic implements Seriali n = 0; value = Double.NaN; } - + /** * Copy constructor, creates a new {@code Min} identical * to the {@code original} - * + * * @param original the {@code Min} instance to copy */ public Min(Min original) { copy(original, this); } - + /** * {@inheritDoc} */ @@ -100,7 +100,7 @@ public class Min extends AbstractStorelessUnivariateStatistic implements Seriali public long getN() { return n; } - + /** * Returns the minimum of the entries in the specified portion of * the input array, or Double.NaN if the designated subarray @@ -110,12 +110,12 @@ public class Min extends AbstractStorelessUnivariateStatistic implements Seriali * the array index parameters are not valid.

*

*

    - *
  • The result is NaN iff all values are NaN + *
  • The result is NaN iff all values are NaN * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.NEGATIVE_INFINITY, + *
  • If any of the values equals Double.NEGATIVE_INFINITY, * the result is Double.NEGATIVE_INFINITY.
  • *

- * + * * @param values the input array * @param begin index of the first array element to include * @param length the number of elements to include @@ -136,7 +136,7 @@ public class Min extends AbstractStorelessUnivariateStatistic implements Seriali } return min; } - + /** * {@inheritDoc} */ @@ -146,11 +146,11 @@ public class Min extends AbstractStorelessUnivariateStatistic implements Seriali copy(this, result); return result; } - + /** * Copies source to dest. *

Neither source nor dest can be null.

- * + * * @param source Min to copy * @param dest Min to copy to * @throws NullPointerException if either source or dest is null diff --git a/src/main/java/org/apache/commons/math/stat/descriptive/rank/Percentile.java b/src/main/java/org/apache/commons/math/stat/descriptive/rank/Percentile.java index 267ed018d..2fef265f0 100644 --- a/src/main/java/org/apache/commons/math/stat/descriptive/rank/Percentile.java +++ b/src/main/java/org/apache/commons/math/stat/descriptive/rank/Percentile.java @@ -25,21 +25,21 @@ import org.apache.commons.math.stat.descriptive.AbstractUnivariateStatistic; /** * Provides percentile computation. *

- * There are several commonly used methods for estimating percentiles (a.k.a. - * quantiles) based on sample data. For large samples, the different methods + * There are several commonly used methods for estimating percentiles (a.k.a. + * quantiles) based on sample data. For large samples, the different methods * agree closely, but when sample sizes are small, different methods will give * significantly different results. The algorithm implemented here works as follows: *

    - *
  1. Let n be the length of the (sorted) array and + *
  2. Let n be the length of the (sorted) array and * 0 < p <= 100 be the desired percentile.
  3. - *
  4. If n = 1 return the unique array element (regardless of + *
  5. If n = 1 return the unique array element (regardless of * the value of p); otherwise
  6. - *
  7. Compute the estimated percentile position + *
  8. Compute the estimated percentile position * pos = p * (n + 1) / 100 and the difference, d * between pos and floor(pos) (i.e. the fractional * part of pos). If pos >= n return the largest * element in the array; otherwise
  9. - *
  10. Let lower be the element in position + *
  11. Let lower be the element in position * floor(pos) in the array and let upper be the * next element in the array. Return lower + d * (upper - lower) *
  12. @@ -48,29 +48,29 @@ import org.apache.commons.math.stat.descriptive.AbstractUnivariateStatistic; * To compute percentiles, the data must be (totally) ordered. Input arrays * are copied and then sorted using {@link java.util.Arrays#sort(double[])}. * The ordering used by Arrays.sort(double[]) is the one determined - * by {@link java.lang.Double#compareTo(Double)}. This ordering makes - * Double.NaN larger than any other value (including + * by {@link java.lang.Double#compareTo(Double)}. This ordering makes + * Double.NaN larger than any other value (including * Double.POSITIVE_INFINITY). Therefore, for example, the median - * (50th percentile) of + * (50th percentile) of * {0, 1, 2, 3, 4, Double.NaN} evaluates to 2.5.

    *

    - * Since percentile estimation usually involves interpolation between array + * Since percentile estimation usually involves interpolation between array * elements, arrays containing NaN or infinite values will often * result in NaN or infinite values returned.

    *

    - * Note that this implementation is not synchronized. If + * Note that this implementation is not synchronized. If * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or + * one of the threads invokes the increment() or * clear() method, it must be synchronized externally.

    - * + * * @version $Revision$ $Date$ */ public class Percentile extends AbstractUnivariateStatistic implements Serializable { /** Serializable version identifier */ - private static final long serialVersionUID = -8091216485095130416L; - - /** Determines what percentile is computed when evaluate() is activated + private static final long serialVersionUID = -8091216485095130416L; + + /** Determines what percentile is computed when evaluate() is activated * with no quantile argument */ private double quantile = 0.0; @@ -95,13 +95,13 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa /** * Copy constructor, creates a new {@code Percentile} identical * to the {@code original} - * + * * @param original the {@code Percentile} instance to copy */ public Percentile(Percentile original) { copy(original, this); - } - + } + /** * Returns an estimate of the pth percentile of the values * in the values array. @@ -110,7 +110,7 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa * state of this statistic.

    *

    *

      - *
    • Returns Double.NaN if values has length + *
    • Returns Double.NaN if values has length * 0
    • *
    • Returns (for any value of p) values[0] * if values has length 1
    • @@ -121,11 +121,11 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa *

      * See {@link Percentile} for a description of the percentile estimation * algorithm used.

      - * + * * @param values input array of values * @param p the percentile value to compute * @return the percentile value or Double.NaN if the array is empty - * @throws IllegalArgumentException if values is null + * @throws IllegalArgumentException if values is null * or p is invalid */ public double evaluate(final double[] values, final double p) { @@ -140,22 +140,22 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa *

      *

        *
      • Returns Double.NaN if length = 0
      • - *
      • Returns (for any value of quantile) + *
      • Returns (for any value of quantile) * values[begin] if length = 1
      • *
      • Throws IllegalArgumentException if values - * is null, or start or length + * is null, or start or length * is invalid
      • *

      *

      * See {@link Percentile} for a description of the percentile estimation * algorithm used.

      - * + * * @param values the input array * @param start index of the first array element to include * @param length the number of elements to include * @return the percentile value * @throws IllegalArgumentException if the parameters are not valid - * + * */ @Override public double evaluate( final double[] values, final int start, final int length) { @@ -176,14 +176,14 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa *
    • Returns (for any value of p) values[begin] * if length = 1
    • *
    • Throws IllegalArgumentException if values - * is null , begin or length is invalid, or + * is null , begin or length is invalid, or * p is not a valid quantile value (p must be greater than 0 * and less than or equal to 100)
    • *

    *

    * See {@link Percentile} for a description of the percentile estimation * algorithm used.

    - * + * * @param values array of input values * @param p the percentile to compute * @param begin the first (0-based) element to include in the computation @@ -192,7 +192,7 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa * @throws IllegalArgumentException if the parameters are not valid or the * input array is null */ - public double evaluate(final double[] values, final int begin, + public double evaluate(final double[] values, final int begin, final int length, final double p) { test(values, begin, length); @@ -230,7 +230,7 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa /** * Returns the value of the quantile field (determines what percentile is * computed when evaluate() is called with no quantile argument). - * + * * @return quantile */ public double getQuantile() { @@ -238,10 +238,10 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa } /** - * Sets the value of the quantile field (determines what percentile is + * Sets the value of the quantile field (determines what percentile is * computed when evaluate() is called with no quantile argument). - * - * @param p a value between 0 < p <= 100 + * + * @param p a value between 0 < p <= 100 * @throws IllegalArgumentException if p is not greater than 0 and less * than or equal to 100 */ @@ -252,7 +252,7 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa } quantile = p; } - + /** * {@inheritDoc} */ @@ -262,11 +262,11 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa copy(this, result); return result; } - + /** * Copies source to dest. *

    Neither source nor dest can be null.

    - * + * * @param source Percentile to copy * @param dest Percentile to copy to * @throws NullPointerException if either source or dest is null diff --git a/src/main/java/org/apache/commons/math/stat/descriptive/summary/Product.java b/src/main/java/org/apache/commons/math/stat/descriptive/summary/Product.java index f21d3f5a0..bf2ef7128 100644 --- a/src/main/java/org/apache/commons/math/stat/descriptive/summary/Product.java +++ b/src/main/java/org/apache/commons/math/stat/descriptive/summary/Product.java @@ -23,24 +23,24 @@ import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStati /** * Returns the product of the available values. *

    - * If there are no values in the dataset, or any of the values are + * If there are no values in the dataset, or any of the values are * NaN, then NaN is returned.

    *

    - * Note that this implementation is not synchronized. If + * Note that this implementation is not synchronized. If * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or + * one of the threads invokes the increment() or * clear() method, it must be synchronized externally.

    - * + * * @version $Revision$ $Date$ */ public class Product extends AbstractStorelessUnivariateStatistic implements Serializable { /** Serializable version identifier */ - private static final long serialVersionUID = 2824226005990582538L; - + private static final long serialVersionUID = 2824226005990582538L; + /**The number of values that have been added */ private long n; - + /** * The current Running Product. */ @@ -131,7 +131,7 @@ public class Product extends AbstractStorelessUnivariateStatistic implements Ser *

    Returns the weighted product of the entries in the specified portion of * the input array, or Double.NaN if the designated subarray * is empty.

    - * + * *

    Throws IllegalArgumentException if any of the following are true: *

    • the values array is null
    • *
    • the weights array is null
    • @@ -141,7 +141,7 @@ public class Product extends AbstractStorelessUnivariateStatistic implements Ser *
    • the weights array contains negative values
    • *
    • the start and length arguments do not determine a valid array
    • *

    - * + * *

    Uses the formula,

          *    weighted product = ∏values[i]weights[i]
          * 
    diff --git a/src/main/java/org/apache/commons/math/stat/descriptive/summary/Sum.java b/src/main/java/org/apache/commons/math/stat/descriptive/summary/Sum.java index ef41ac7eb..7a7fdeb5c 100644 --- a/src/main/java/org/apache/commons/math/stat/descriptive/summary/Sum.java +++ b/src/main/java/org/apache/commons/math/stat/descriptive/summary/Sum.java @@ -23,24 +23,24 @@ import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStati /** * Returns the sum of the available values. *

    - * If there are no values in the dataset, or any of the values are + * If there are no values in the dataset, or any of the values are * NaN, then NaN is returned.

    *

    - * Note that this implementation is not synchronized. If + * Note that this implementation is not synchronized. If * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or + * one of the threads invokes the increment() or * clear() method, it must be synchronized externally.

    - * + * * @version $Revision$ $Date$ */ public class Sum extends AbstractStorelessUnivariateStatistic implements Serializable { /** Serializable version identifier */ - private static final long serialVersionUID = -8231831954703408316L; - + private static final long serialVersionUID = -8231831954703408316L; + /** */ private long n; - + /** * The currently running sum. */ diff --git a/src/main/java/org/apache/commons/math/stat/descriptive/summary/SumOfLogs.java b/src/main/java/org/apache/commons/math/stat/descriptive/summary/SumOfLogs.java index ac6564f4f..56a920de1 100644 --- a/src/main/java/org/apache/commons/math/stat/descriptive/summary/SumOfLogs.java +++ b/src/main/java/org/apache/commons/math/stat/descriptive/summary/SumOfLogs.java @@ -21,39 +21,39 @@ import java.io.Serializable; import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStatistic; /** - * Returns the sum of the natural logs for this collection of values. + * Returns the sum of the natural logs for this collection of values. *

    * Uses {@link java.lang.Math#log(double)} to compute the logs. Therefore, *

      *
    • If any of values are < 0, the result is NaN.
    • - *
    • If all values are non-negative and less than + *
    • If all values are non-negative and less than * Double.POSITIVE_INFINITY, but at least one value is 0, the * result is Double.NEGATIVE_INFINITY.
    • - *
    • If both Double.POSITIVE_INFINITY and + *
    • If both Double.POSITIVE_INFINITY and * Double.NEGATIVE_INFINITY are among the values, the result is * NaN.
    • *

    *

    - * Note that this implementation is not synchronized. If + * Note that this implementation is not synchronized. If * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or + * one of the threads invokes the increment() or * clear() method, it must be synchronized externally.

    - * + * * @version $Revision$ $Date$ */ public class SumOfLogs extends AbstractStorelessUnivariateStatistic implements Serializable { /** Serializable version identifier */ - private static final long serialVersionUID = -370076995648386763L; + private static final long serialVersionUID = -370076995648386763L; /**Number of values that have been added */ private int n; - + /** * The currently running value */ private double value; - + /** * Create a SumOfLogs instance */ @@ -61,11 +61,11 @@ public class SumOfLogs extends AbstractStorelessUnivariateStatistic implements S value = 0d; n = 0; } - + /** * Copy constructor, creates a new {@code SumOfLogs} identical * to the {@code original} - * + * * @param original the {@code SumOfLogs} instance to copy */ public SumOfLogs(SumOfLogs original) { @@ -99,7 +99,7 @@ public class SumOfLogs extends AbstractStorelessUnivariateStatistic implements S public long getN() { return n; } - + /** * {@inheritDoc} */ @@ -117,11 +117,11 @@ public class SumOfLogs extends AbstractStorelessUnivariateStatistic implements S * Throws IllegalArgumentException if the array is null.

    *

    * See {@link SumOfLogs}.

    - * + * * @param values the input array * @param begin index of the first array element to include * @param length the number of elements to include - * @return the sum of the natural logs of the values or Double.NaN if + * @return the sum of the natural logs of the values or Double.NaN if * length = 0 * @throws IllegalArgumentException if the array is null or the array index * parameters are not valid @@ -137,7 +137,7 @@ public class SumOfLogs extends AbstractStorelessUnivariateStatistic implements S } return sumLog; } - + /** * {@inheritDoc} */ @@ -147,11 +147,11 @@ public class SumOfLogs extends AbstractStorelessUnivariateStatistic implements S copy(this, result); return result; } - + /** * Copies source to dest. *

    Neither source nor dest can be null.

    - * + * * @param source SumOfLogs to copy * @param dest SumOfLogs to copy to * @throws NullPointerException if either source or dest is null diff --git a/src/main/java/org/apache/commons/math/stat/descriptive/summary/SumOfSquares.java b/src/main/java/org/apache/commons/math/stat/descriptive/summary/SumOfSquares.java index 9d616c7b5..a1429f974 100644 --- a/src/main/java/org/apache/commons/math/stat/descriptive/summary/SumOfSquares.java +++ b/src/main/java/org/apache/commons/math/stat/descriptive/summary/SumOfSquares.java @@ -23,24 +23,24 @@ import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStati /** * Returns the sum of the squares of the available values. *

    - * If there are no values in the dataset, or any of the values are + * If there are no values in the dataset, or any of the values are * NaN, then NaN is returned.

    *

    - * Note that this implementation is not synchronized. If + * Note that this implementation is not synchronized. If * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or + * one of the threads invokes the increment() or * clear() method, it must be synchronized externally.

    - * + * * @version $Revision$ $Date$ */ public class SumOfSquares extends AbstractStorelessUnivariateStatistic implements Serializable { /** Serializable version identifier */ - private static final long serialVersionUID = 1460986908574398008L; - + private static final long serialVersionUID = 1460986908574398008L; + /** */ private long n; - + /** * The currently running sumSq */ @@ -53,17 +53,17 @@ public class SumOfSquares extends AbstractStorelessUnivariateStatistic implement n = 0; value = Double.NaN; } - + /** * Copy constructor, creates a new {@code SumOfSquares} identical * to the {@code original} - * + * * @param original the {@code SumOfSquares} instance to copy */ public SumOfSquares(SumOfSquares original) { copy(original, this); } - + /** * {@inheritDoc} */ @@ -91,7 +91,7 @@ public class SumOfSquares extends AbstractStorelessUnivariateStatistic implement public long getN() { return n; } - + /** * {@inheritDoc} */ @@ -107,7 +107,7 @@ public class SumOfSquares extends AbstractStorelessUnivariateStatistic implement * is empty. *

    * Throws IllegalArgumentException if the array is null.

    - * + * * @param values the input array * @param begin index of the first array element to include * @param length the number of elements to include @@ -126,7 +126,7 @@ public class SumOfSquares extends AbstractStorelessUnivariateStatistic implement } return sumSq; } - + /** * {@inheritDoc} */ @@ -136,11 +136,11 @@ public class SumOfSquares extends AbstractStorelessUnivariateStatistic implement copy(this, result); return result; } - + /** * Copies source to dest. *

    Neither source nor dest can be null.

    - * + * * @param source SumOfSquares to copy * @param dest SumOfSquares to copy to * @throws NullPointerException if either source or dest is null diff --git a/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTest.java b/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTest.java index 906abd6ba..892eac2be 100644 --- a/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTest.java +++ b/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTest.java @@ -23,27 +23,27 @@ import org.apache.commons.math.MathException; *

    This interface handles only known distributions. If the distribution is * unknown and should be provided by a sample, then the {@link UnknownDistributionChiSquareTest * UnknownDistributionChiSquareTest} extended interface should be used instead.

    - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public interface ChiSquareTest { - + /** * Computes the - * Chi-Square statistic comparing observed and expected - * frequency counts. + * Chi-Square statistic comparing observed and expected + * frequency counts. *

    * This statistic can be used to perform a Chi-Square test evaluating the null hypothesis that * the observed counts follow the expected distribution.

    *

    * Preconditions:

      - *
    • Expected counts must all be positive. + *
    • Expected counts must all be positive. *
    • - *
    • Observed counts must all be >= 0. + *
    • Observed counts must all be >= 0. *
    • *
    • The observed and expected arrays must have the same length and - * their common length must be at least 2. + * their common length must be at least 2. *

    - * If any of the preconditions are not met, an + * If any of the preconditions are not met, an * IllegalArgumentException is thrown.

    * * @param observed array of observed frequency counts @@ -51,30 +51,30 @@ public interface ChiSquareTest { * @return chiSquare statistic * @throws IllegalArgumentException if preconditions are not met */ - double chiSquare(double[] expected, long[] observed) + double chiSquare(double[] expected, long[] observed) throws IllegalArgumentException; - + /** * Returns the observed significance level, or - * p-value, associated with a + * p-value, associated with a * - * Chi-square goodness of fit test comparing the observed + * Chi-square goodness of fit test comparing the observed * frequency counts to those in the expected array. *

    - * The number returned is the smallest significance level at which one can reject - * the null hypothesis that the observed counts conform to the frequency distribution + * The number returned is the smallest significance level at which one can reject + * the null hypothesis that the observed counts conform to the frequency distribution * described by the expected counts.

    *

    * Preconditions:

      - *
    • Expected counts must all be positive. + *
    • Expected counts must all be positive. *
    • - *
    • Observed counts must all be >= 0. + *
    • Observed counts must all be >= 0. *
    • *
    • The observed and expected arrays must have the same length and - * their common length must be at least 2. + * their common length must be at least 2. *

    - * If any of the preconditions are not met, an + * If any of the preconditions are not met, an * IllegalArgumentException is thrown.

    * * @param observed array of observed frequency counts @@ -83,31 +83,31 @@ public interface ChiSquareTest { * @throws IllegalArgumentException if preconditions are not met * @throws MathException if an error occurs computing the p-value */ - double chiSquareTest(double[] expected, long[] observed) + double chiSquareTest(double[] expected, long[] observed) throws IllegalArgumentException, MathException; - + /** * Performs a - * Chi-square goodness of fit test evaluating the null hypothesis that the observed counts - * conform to the frequency distribution described by the expected counts, with + * Chi-square goodness of fit test evaluating the null hypothesis that the observed counts + * conform to the frequency distribution described by the expected counts, with * significance level alpha. Returns true iff the null hypothesis can be rejected * with 100 * (1 - alpha) percent confidence. *

    * Example:
    - * To test the hypothesis that observed follows + * To test the hypothesis that observed follows * expected at the 99% level, use

    * chiSquareTest(expected, observed, 0.01)

    *

    * Preconditions:

      - *
    • Expected counts must all be positive. + *
    • Expected counts must all be positive. *
    • - *
    • Observed counts must all be >= 0. + *
    • Observed counts must all be >= 0. *
    • *
    • The observed and expected arrays must have the same length and - * their common length must be at least 2. + * their common length must be at least 2. *
    • 0 < alpha < 0.5 *

    - * If any of the preconditions are not met, an + * If any of the preconditions are not met, an * IllegalArgumentException is thrown.

    * * @param observed array of observed frequency counts @@ -118,59 +118,59 @@ public interface ChiSquareTest { * @throws IllegalArgumentException if preconditions are not met * @throws MathException if an error occurs performing the test */ - boolean chiSquareTest(double[] expected, long[] observed, double alpha) + boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws IllegalArgumentException, MathException; - + /** - * Computes the Chi-Square statistic associated with a + * Computes the Chi-Square statistic associated with a * * chi-square test of independence based on the input counts - * array, viewed as a two-way table. + * array, viewed as a two-way table. *

    - * The rows of the 2-way table are + * The rows of the 2-way table are * count[0], ... , count[count.length - 1]

    *

    * Preconditions:

      - *
    • All counts must be >= 0. + *
    • All counts must be >= 0. *
    • *
    • The count array must be rectangular (i.e. all count[i] subarrays - * must have the same length). + * must have the same length). *
    • *
    • The 2-way table represented by counts must have at * least 2 columns and at least 2 rows. *
    • *

    - * If any of the preconditions are not met, an + * If any of the preconditions are not met, an * IllegalArgumentException is thrown.

    * * @param counts array representation of 2-way table * @return chiSquare statistic * @throws IllegalArgumentException if preconditions are not met */ - double chiSquare(long[][] counts) + double chiSquare(long[][] counts) throws IllegalArgumentException; - + /** * Returns the observed significance level, or - * p-value, associated with a + * p-value, associated with a * * chi-square test of independence based on the input counts - * array, viewed as a two-way table. + * array, viewed as a two-way table. *

    - * The rows of the 2-way table are + * The rows of the 2-way table are * count[0], ... , count[count.length - 1]

    *

    * Preconditions:

      - *
    • All counts must be >= 0. + *
    • All counts must be >= 0. *
    • - *
    • The count array must be rectangular (i.e. all count[i] subarrays must have the same length). + *
    • The count array must be rectangular (i.e. all count[i] subarrays must have the same length). *
    • *
    • The 2-way table represented by counts must have at least 2 columns and * at least 2 rows. *
    • *

    - * If any of the preconditions are not met, an + * If any of the preconditions are not met, an * IllegalArgumentException is thrown.

    * * @param counts array representation of 2-way table @@ -178,17 +178,17 @@ public interface ChiSquareTest { * @throws IllegalArgumentException if preconditions are not met * @throws MathException if an error occurs computing the p-value */ - double chiSquareTest(long[][] counts) + double chiSquareTest(long[][] counts) throws IllegalArgumentException, MathException; - + /** * Performs a - * chi-square test of independence evaluating the null hypothesis that the classifications + * chi-square test of independence evaluating the null hypothesis that the classifications * represented by the counts in the columns of the input 2-way table are independent of the rows, * with significance level alpha. Returns true iff the null hypothesis can be rejected * with 100 * (1 - alpha) percent confidence. *

    - * The rows of the 2-way table are + * The rows of the 2-way table are * count[0], ... , count[count.length - 1]

    *

    * Example:
    @@ -198,15 +198,15 @@ public interface ChiSquareTest { * chiSquareTest(counts, 0.01)

    *

    * Preconditions:

      - *
    • All counts must be >= 0. + *
    • All counts must be >= 0. *
    • - *
    • The count array must be rectangular (i.e. all count[i] subarrays must have the same length). + *
    • The count array must be rectangular (i.e. all count[i] subarrays must have the same length). *
    • *
    • The 2-way table represented by counts must have at least 2 columns and * at least 2 rows. *
    • *

    - * If any of the preconditions are not met, an + * If any of the preconditions are not met, an * IllegalArgumentException is thrown.

    * * @param counts array representation of 2-way table @@ -216,7 +216,7 @@ public interface ChiSquareTest { * @throws IllegalArgumentException if preconditions are not met * @throws MathException if an error occurs performing the test */ - boolean chiSquareTest(long[][] counts, double alpha) + boolean chiSquareTest(long[][] counts, double alpha) throws IllegalArgumentException, MathException; } diff --git a/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java b/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java index fa8879035..fe10cecf1 100644 --- a/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java +++ b/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java @@ -31,9 +31,9 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { /** Distribution used to compute inference statistics. */ private ChiSquaredDistribution distribution; - + /** - * Construct a ChiSquareTestImpl + * Construct a ChiSquareTestImpl */ public ChiSquareTestImpl() { this(new ChiSquaredDistributionImpl(1.0)); @@ -51,10 +51,10 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { } /** * {@inheritDoc} - *

    Note: This implementation rescales the + *

    Note: This implementation rescales the * expected array if necessary to ensure that the sum of the * expected and observed counts are equal.

    - * + * * @param observed array of observed frequency counts * @param expected array of expected frequency counts * @return chi-square test statistic @@ -102,10 +102,10 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { /** * {@inheritDoc} - *

    Note: This implementation rescales the + *

    Note: This implementation rescales the * expected array if necessary to ensure that the sum of the * expected and observed counts are equal.

    - * + * * @param observed array of observed frequency counts * @param expected array of expected frequency counts * @return p-value @@ -121,10 +121,10 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { /** * {@inheritDoc} - *

    Note: This implementation rescales the + *

    Note: This implementation rescales the * expected array if necessary to ensure that the sum of the * expected and observed counts are equal.

    - * + * * @param observed array of observed frequency counts * @param expected array of expected frequency counts * @param alpha significance level of the test @@ -133,7 +133,7 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { * @throws IllegalArgumentException if preconditions are not met * @throws MathException if an error occurs performing the test */ - public boolean chiSquareTest(double[] expected, long[] observed, + public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws IllegalArgumentException, MathException { if ((alpha <= 0) || (alpha > 0.5)) { throw MathRuntimeException.createIllegalArgumentException( @@ -142,18 +142,18 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { } return (chiSquareTest(expected, observed) < alpha); } - + /** * @param counts array representation of 2-way table * @return chi-square test statistic * @throws IllegalArgumentException if preconditions are not met */ public double chiSquare(long[][] counts) throws IllegalArgumentException { - + checkArray(counts); int nRows = counts.length; int nCols = counts[0].length; - + // compute row, column and total sums double[] rowSum = new double[nRows]; double[] colSum = new double[nCols]; @@ -165,17 +165,17 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { total += counts[row][col]; } } - + // compute expected counts and chi-square double sumSq = 0.0d; double expected = 0.0d; for (int row = 0; row < nRows; row++) { for (int col = 0; col < nCols; col++) { expected = (rowSum[row] * colSum[col]) / total; - sumSq += ((counts[row][col] - expected) * - (counts[row][col] - expected)) / expected; + sumSq += ((counts[row][col] - expected) * + (counts[row][col] - expected)) / expected; } - } + } return sumSq; } @@ -210,7 +210,7 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { } return (chiSquareTest(counts) < alpha); } - + /** * @param observed1 array of observed frequency counts of the first data set * @param observed2 array of observed frequency counts of the second data set @@ -220,7 +220,7 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { */ public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) throws IllegalArgumentException { - + // Make sure lengths are same if (observed1.length < 2) { throw MathRuntimeException.createIllegalArgumentException( @@ -244,16 +244,16 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { double weight = 0.0; for (int i = 0; i < observed1.length; i++) { countSum1 += observed1[i]; - countSum2 += observed2[i]; + countSum2 += observed2[i]; } // Ensure neither sample is uniformly 0 if (countSum1 == 0) { throw MathRuntimeException.createIllegalArgumentException( - "observed counts are all 0 in first observed array"); + "observed counts are all 0 in first observed array"); } if (countSum2 == 0) { throw MathRuntimeException.createIllegalArgumentException( - "observed counts are all 0 in second observed array"); + "observed counts are all 0 in second observed array"); } // Compare and compute weight only if different unequalCounts = (countSum1 != countSum2); @@ -322,34 +322,34 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { * Checks to make sure that the input long[][] array is rectangular, * has at least 2 rows and 2 columns, and has all non-negative entries, * throwing IllegalArgumentException if any of these checks fail. - * + * * @param in input 2-way table to check * @throws IllegalArgumentException if the array is not valid */ private void checkArray(long[][] in) throws IllegalArgumentException { - + if (in.length < 2) { throw MathRuntimeException.createIllegalArgumentException( "invalid row dimension: {0} (must be at least 2)", in.length); } - + if (in[0].length < 2) { throw MathRuntimeException.createIllegalArgumentException( "invalid column dimension: {0} (must be at least 2)", in[0].length); - } - + } + checkRectangular(in); checkNonNegative(in); - + } - + //--------------------- Private array methods -- should find a utility home for these - + /** * Throws IllegalArgumentException if the input array is not rectangular. - * + * * @param in array to be tested * @throws NullPointerException if input array is null * @throws IllegalArgumentException if input array is not rectangular @@ -361,12 +361,12 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { "some rows have length {0} while others have length {1}", in[i].length, in[0].length); } - } + } } - + /** * Check all entries of the input array are > 0. - * + * * @param in array to be tested * @exception IllegalArgumentException if one entry is not positive */ @@ -379,10 +379,10 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { } } } - + /** * Check all entries of the input array are >= 0. - * + * * @param in array to be tested * @exception IllegalArgumentException if one entry is negative */ @@ -395,10 +395,10 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { } } } - + /** * Check all entries of the input array are >= 0. - * + * * @param in array to be tested * @exception IllegalArgumentException if one entry is negative */ @@ -413,10 +413,10 @@ public class ChiSquareTestImpl implements UnknownDistributionChiSquareTest { } } } - + /** * Modify the distribution used to compute inference statistics. - * + * * @param value * the new distribution * @since 1.2 diff --git a/src/main/java/org/apache/commons/math/stat/inference/OneWayAnova.java b/src/main/java/org/apache/commons/math/stat/inference/OneWayAnova.java index becaf21ef..d2776ccce 100644 --- a/src/main/java/org/apache/commons/math/stat/inference/OneWayAnova.java +++ b/src/main/java/org/apache/commons/math/stat/inference/OneWayAnova.java @@ -20,7 +20,7 @@ import org.apache.commons.math.MathException; import java.util.Collection; /** - * An interface for one-way ANOVA (analysis of variance). + * An interface for one-way ANOVA (analysis of variance). * *

    Tests for differences between two or more categories of univariate data * (for example, the body mass index of accountants, lawyers, doctors and @@ -29,13 +29,13 @@ import java.util.Collection; *

    * * @since 1.2 - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public interface OneWayAnova { /** * Computes the ANOVA F-value for a collection of double[] * arrays. - * + * *

    Preconditions:

      *
    • The categoryData Collection must contain * double[] arrays.
    • @@ -77,7 +77,7 @@ public interface OneWayAnova { /** * Performs an ANOVA test, evaluating the null hypothesis that there * is no difference among the means of the data categories. - * + * *

      Preconditions:

        *
      • The categoryData Collection must contain * double[] arrays.
      • @@ -90,7 +90,7 @@ public interface OneWayAnova { * @param categoryData Collection of double[] * arrays each containing data for one category * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if the statistic can not be computed do to a @@ -99,4 +99,4 @@ public interface OneWayAnova { public boolean anovaTest(Collection categoryData, double alpha) throws IllegalArgumentException, MathException; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/math/stat/inference/OneWayAnovaImpl.java b/src/main/java/org/apache/commons/math/stat/inference/OneWayAnovaImpl.java index 99c216b52..27a00773e 100644 --- a/src/main/java/org/apache/commons/math/stat/inference/OneWayAnovaImpl.java +++ b/src/main/java/org/apache/commons/math/stat/inference/OneWayAnovaImpl.java @@ -29,12 +29,12 @@ import org.apache.commons.math.stat.descriptive.summary.SumOfSquares; /** * Implements one-way ANOVA statistics defined in the {@link OneWayAnovaImpl} * interface. - * - *

        Uses the + * + *

        Uses the * {@link org.apache.commons.math.distribution.FDistribution * commons-math F Distribution implementation} to estimate exact p-values.

        * - *

        This implementation is based on a description at + *

        This implementation is based on a description at * http://faculty.vassar.edu/lowry/ch13pt1.html

        *
          * Abbreviations: bg = between groups,
        @@ -52,10 +52,10 @@ public class OneWayAnovaImpl implements OneWayAnova  {
              */
             public OneWayAnovaImpl() {
             }
        -    
        +
             /**
              * {@inheritDoc}

        - * This implementation computes the F statistic using the definitional + * This implementation computes the F statistic using the definitional * formula

              *   F = msbg/mswg
        * where
        @@ -111,7 +111,7 @@ public class OneWayAnovaImpl implements OneWayAnova  {
         
             /**
              * This method actually does the calculations (except P-value).
        -     * 
        +     *
              * @param categoryData Collection of double[]
              * arrays each containing data for one category
              * @return computed AnovaStats
        @@ -128,7 +128,7 @@ public class OneWayAnovaImpl implements OneWayAnova  {
                           "two or more categories required, got {0}",
                           categoryData.size());
                 }
        -        
        +
                 // check if each category has enough data and all is double[]
                 for (double[] array : categoryData) {
                     if (array.length <= 1) {
        @@ -143,7 +143,7 @@ public class OneWayAnovaImpl implements OneWayAnova  {
                 Sum totsum = new Sum();
                 SumOfSquares totsumsq = new SumOfSquares();
                 int totnum = 0;
        -        
        +
                 for (double[] data : categoryData) {
         
                     Sum sum = new Sum();
        @@ -167,7 +167,7 @@ public class OneWayAnovaImpl implements OneWayAnova  {
                     double ss = sumsq.getResult() - sum.getResult() * sum.getResult() / num;
                     sswg += ss;
                 }
        -        double sst = totsumsq.getResult() - totsum.getResult() * 
        +        double sst = totsumsq.getResult() - totsum.getResult() *
                     totsum.getResult()/totnum;
                 double ssbg = sst - sswg;
                 int dfbg = categoryData.size() - 1;
        @@ -178,7 +178,7 @@ public class OneWayAnovaImpl implements OneWayAnova  {
                 return new AnovaStats(dfbg, dfwg, F);
             }
         
        -    /** 
        +    /**
                 Convenience class to pass dfbg,dfwg,F values around within AnovaImpl.
                 No get/set methods provided.
             */
        @@ -206,4 +206,4 @@ public class OneWayAnovaImpl implements OneWayAnova  {
                 }
             }
         
        -}
        \ No newline at end of file
        +}
        diff --git a/src/main/java/org/apache/commons/math/stat/inference/TTest.java b/src/main/java/org/apache/commons/math/stat/inference/TTest.java
        index 7447391d1..404a55a41 100644
        --- a/src/main/java/org/apache/commons/math/stat/inference/TTest.java
        +++ b/src/main/java/org/apache/commons/math/stat/inference/TTest.java
        @@ -38,19 +38,19 @@ import org.apache.commons.math.stat.descriptive.StatisticalSummary;
          * Significance levels are always specified as numbers between 0 and 0.5
          * (e.g. tests at the 95% level  use alpha=0.05).

        *

        - * Input to tests can be either double[] arrays or + * Input to tests can be either double[] arrays or * {@link StatisticalSummary} instances.

        - * * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public interface TTest { /** - * Computes a paired, 2-sample t-statistic based on the data in the input + * Computes a paired, 2-sample t-statistic based on the data in the input * arrays. The t-statistic returned is equivalent to what would be returned by * computing the one-sample t-statistic {@link #t(double, double[])}, with - * mu = 0 and the sample array consisting of the (signed) - * differences between corresponding entries in sample1 and + * mu = 0 and the sample array consisting of the (signed) + * differences between corresponding entries in sample1 and * sample2. *

        * Preconditions:

          @@ -68,24 +68,24 @@ public interface TTest { public abstract double pairedT(double[] sample1, double[] sample2) throws IllegalArgumentException, MathException; /** - * Returns the observed significance level, or - * p-value, associated with a paired, two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a paired, two-sample, two-tailed t-test * based on the data in the input arrays. *

          * The number returned is the smallest significance level * at which one can reject the null hypothesis that the mean of the paired - * differences is 0 in favor of the two-sided alternative that the mean paired - * difference is not equal to 0. For a one-sided test, divide the returned + * differences is 0 in favor of the two-sided alternative that the mean paired + * difference is not equal to 0. For a one-sided test, divide the returned * value by 2.

          *

          * This test is equivalent to a one-sample t-test computed using * {@link #tTest(double, double[])} with mu = 0 and the sample - * array consisting of the signed differences between corresponding elements of + * array consisting of the signed differences between corresponding elements of * sample1 and sample2.

          *

          * Usage Note:
          * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

          *

          @@ -103,24 +103,24 @@ public interface TTest { public abstract double pairedTTest(double[] sample1, double[] sample2) throws IllegalArgumentException, MathException; /** - * Performs a paired t-test evaluating the null hypothesis that the + * Performs a paired t-test evaluating the null hypothesis that the * mean of the paired differences between sample1 and - * sample2 is 0 in favor of the two-sided alternative that the - * mean paired difference is not equal to 0, with significance level + * sample2 is 0 in favor of the two-sided alternative that the + * mean paired difference is not equal to 0, with significance level * alpha. *

          - * Returns true iff the null hypothesis can be rejected with - * confidence 1 - alpha. To perform a 1-sided test, use + * Returns true iff the null hypothesis can be rejected with + * confidence 1 - alpha. To perform a 1-sided test, use * alpha * 2

          *

          * Usage Note:
          * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

          *

          * Preconditions:

            - *
          • The input array lengths must be the same and their common length + *
          • The input array lengths must be the same and their common length * must be at least 2. *
          • *
          • 0 < alpha < 0.5 @@ -129,7 +129,7 @@ public interface TTest { * @param sample1 array of sample data values * @param sample2 array of sample data values * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if an error occurs performing the test @@ -140,7 +140,7 @@ public interface TTest { double alpha) throws IllegalArgumentException, MathException; /** - * Computes a + * Computes a * t statistic given observed values and a comparison constant. *

            * This statistic can be used to perform a one sample t-test for the mean. @@ -158,7 +158,7 @@ public interface TTest { throws IllegalArgumentException; /** * Computes a - * t statistic to use in comparing the mean of the dataset described by + * t statistic to use in comparing the mean of the dataset described by * sampleStats to mu. *

            * This statistic can be used to perform a one sample t-test for the mean. @@ -175,7 +175,7 @@ public interface TTest { public abstract double t(double mu, StatisticalSummary sampleStats) throws IllegalArgumentException; /** - * Computes a 2-sample t statistic, under the hypothesis of equal + * Computes a 2-sample t statistic, under the hypothesis of equal * subpopulation variances. To compute a t-statistic without the * equal variances hypothesis, use {@link #t(double[], double[])}. *

            @@ -186,15 +186,15 @@ public interface TTest { *

            *    t = (m1 - m2) / (sqrt(1/n1 +1/n2) sqrt(var)) *

            - * where n1 is the size of first sample; - * n2 is the size of second sample; - * m1 is the mean of first sample; + * where n1 is the size of first sample; + * n2 is the size of second sample; + * m1 is the mean of first sample; * m2 is the mean of second sample

          • *
          * and var is the pooled variance estimate: *

          * var = sqrt(((n1 - 1)var1 + (n2 - 1)var2) / ((n1-1) + (n2-1))) - *

          + *

          * with var1 the variance of the first sample and * var2 the variance of the second sample. *

          @@ -222,11 +222,11 @@ public interface TTest { *    t = (m1 - m2) / sqrt(var1/n1 + var2/n2) *

          * where n1 is the size of the first sample - * n2 is the size of the second sample; - * m1 is the mean of the first sample; + * n2 is the size of the second sample; + * m1 is the mean of the first sample; * m2 is the mean of the second sample; * var1 is the variance of the first sample; - * var2 is the variance of the second sample; + * var2 is the variance of the second sample; *

          * Preconditions:

            *
          • The observed array lengths must both be at least 2. @@ -242,7 +242,7 @@ public interface TTest { /** * Computes a 2-sample t statistic , comparing the means of the datasets * described by two {@link StatisticalSummary} instances, without the - * assumption of equal subpopulation variances. Use + * assumption of equal subpopulation variances. Use * {@link #homoscedasticT(StatisticalSummary, StatisticalSummary)} to * compute a t-statistic under the equal variances assumption. *

            @@ -253,11 +253,11 @@ public interface TTest { *

            *    t = (m1 - m2) / sqrt(var1/n1 + var2/n2) *

            - * where n1 is the size of the first sample; - * n2 is the size of the second sample; - * m1 is the mean of the first sample; + * where n1 is the size of the first sample; + * n2 is the size of the second sample; + * m1 is the mean of the first sample; * m2 is the mean of the second sample - * var1 is the variance of the first sample; + * var1 is the variance of the first sample; * var2 is the variance of the second sample *

            * Preconditions:

              @@ -278,7 +278,7 @@ public interface TTest { * Computes a 2-sample t statistic, comparing the means of the datasets * described by two {@link StatisticalSummary} instances, under the * assumption of equal subpopulation variances. To compute a t-statistic - * without the equal variances assumption, use + * without the equal variances assumption, use * {@link #t(StatisticalSummary, StatisticalSummary)}. *

              * This statistic can be used to perform a (homoscedastic) two-sample @@ -288,14 +288,14 @@ public interface TTest { *

              *    t = (m1 - m2) / (sqrt(1/n1 +1/n2) sqrt(var)) *

              - * where n1 is the size of first sample; - * n2 is the size of second sample; - * m1 is the mean of first sample; + * where n1 is the size of first sample; + * n2 is the size of second sample; + * m1 is the mean of first sample; * m2 is the mean of second sample * and var is the pooled variance estimate: *

              * var = sqrt(((n1 - 1)var1 + (n2 - 1)var2) / ((n1-1) + (n2-1))) - *

              + *

              * with var1 the variance of the first sample and * var2 the variance of the second sample. *

              @@ -314,19 +314,19 @@ public interface TTest { StatisticalSummary sampleStats2) throws IllegalArgumentException; /** - * Returns the observed significance level, or - * p-value, associated with a one-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a one-sample, two-tailed t-test * comparing the mean of the input array with the constant mu. *

              * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the mean equals + * at which one can reject the null hypothesis that the mean equals * mu in favor of the two-sided alternative that the mean - * is different from mu. For a one-sided test, divide the + * is different from mu. For a one-sided test, divide the * returned value by 2.

              *

              * Usage Note:
              * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * here *

              * Preconditions:

                @@ -346,8 +346,8 @@ public interface TTest { * two-sided t-test evaluating the null hypothesis that the mean of the population from * which sample is drawn equals mu. *

                - * Returns true iff the null hypothesis can be - * rejected with confidence 1 - alpha. To + * Returns true iff the null hypothesis can be + * rejected with confidence 1 - alpha. To * perform a 1-sided test, use alpha * 2

                *

                * Examples:

                  @@ -355,14 +355,14 @@ public interface TTest { * the 95% level, use
                  tTest(mu, sample, 0.05) * *
                1. To test the (one-sided) hypothesis sample mean < mu - * at the 99% level, first verify that the measured sample mean is less - * than mu and then use + * at the 99% level, first verify that the measured sample mean is less + * than mu and then use *
                  tTest(mu, sample, 0.02) *

                *

                * Usage Note:
                - * The validity of the test depends on the assumptions of the one-sample - * parametric t-test procedure, as discussed + * The validity of the test depends on the assumptions of the one-sample + * parametric t-test procedure, as discussed * here *

                * Preconditions:

                  @@ -379,20 +379,20 @@ public interface TTest { public abstract boolean tTest(double mu, double[] sample, double alpha) throws IllegalArgumentException, MathException; /** - * Returns the observed significance level, or - * p-value, associated with a one-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a one-sample, two-tailed t-test * comparing the mean of the dataset described by sampleStats * with the constant mu. *

                  * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the mean equals + * at which one can reject the null hypothesis that the mean equals * mu in favor of the two-sided alternative that the mean - * is different from mu. For a one-sided test, divide the + * is different from mu. For a one-sided test, divide the * returned value by 2.

                  *

                  * Usage Note:
                  * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

                  *

                  @@ -423,14 +423,14 @@ public interface TTest { * the 95% level, use
                  tTest(mu, sampleStats, 0.05) * *

                • To test the (one-sided) hypothesis sample mean < mu - * at the 99% level, first verify that the measured sample mean is less - * than mu and then use + * at the 99% level, first verify that the measured sample mean is less + * than mu and then use *
                  tTest(mu, sampleStats, 0.02) *

*

* Usage Note:
- * The validity of the test depends on the assumptions of the one-sample - * parametric t-test procedure, as discussed + * The validity of the test depends on the assumptions of the one-sample + * parametric t-test procedure, as discussed * here *

* Preconditions:

    @@ -450,28 +450,28 @@ public interface TTest { double alpha) throws IllegalArgumentException, MathException; /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a two-sample, two-tailed t-test * comparing the means of the input arrays. *

    * The number returned is the smallest significance level * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. + * equal in favor of the two-sided alternative that they are different. * For a one-sided test, divide the returned value by 2.

    *

    * The test does not assume that the underlying popuation variances are - * equal and it uses approximated degrees of freedom computed from the + * equal and it uses approximated degrees of freedom computed from the * sample data to compute the p-value. The t-statistic used is as defined in * {@link #t(double[], double[])} and the Welch-Satterthwaite approximation - * to the degrees of freedom is used, - * as described + * to the degrees of freedom is used, + * as described * * here. To perform the test under the assumption of equal subpopulation * variances, use {@link #homoscedasticTTest(double[], double[])}.

    *

    * Usage Note:
    * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

    *

    @@ -488,8 +488,8 @@ public interface TTest { public abstract double tTest(double[] sample1, double[] sample2) throws IllegalArgumentException, MathException; /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a two-sample, two-tailed t-test * comparing the means of the input arrays, under the assumption that * the two samples are drawn from subpopulations with equal variances. * To perform the test without the equal variances assumption, use @@ -497,7 +497,7 @@ public interface TTest { *

    * The number returned is the smallest significance level * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. + * equal in favor of the two-sided alternative that they are different. * For a one-sided test, divide the returned value by 2.

    *

    * A pooled variance estimate is used to compute the t-statistic. See @@ -506,7 +506,7 @@ public interface TTest { *

    * Usage Note:
    * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

    *

    @@ -525,17 +525,17 @@ public interface TTest { double[] sample2) throws IllegalArgumentException, MathException; /** - * Performs a + * Performs a * - * two-sided t-test evaluating the null hypothesis that sample1 - * and sample2 are drawn from populations with the same mean, + * two-sided t-test evaluating the null hypothesis that sample1 + * and sample2 are drawn from populations with the same mean, * with significance level alpha. This test does not assume * that the subpopulation variances are equal. To perform the test assuming - * equal variances, use + * equal variances, use * {@link #homoscedasticTTest(double[], double[], double)}. *

    * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To + * equal can be rejected with confidence 1 - alpha. To * perform a 1-sided test, use alpha * 2

    *

    * See {@link #t(double[], double[])} for the formula used to compute the @@ -545,18 +545,18 @@ public interface TTest { *

    * Examples:

      *
    1. To test the (2-sided) hypothesis mean 1 = mean 2 at - * the 95% level, use + * the 95% level, use *
      tTest(sample1, sample2, 0.05). *
    2. *
    3. To test the (one-sided) hypothesis mean 1 < mean 2 , * at the 99% level, first verify that the measured mean of sample 1 - * is less than the mean of sample 2 and then use + * is less than the mean of sample 2 and then use *
      tTest(sample1, sample2, 0.02) *

    *

    * Usage Note:
    * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

    *

    @@ -569,7 +569,7 @@ public interface TTest { * @param sample1 array of sample data values * @param sample2 array of sample data values * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if an error occurs performing the test @@ -580,19 +580,19 @@ public interface TTest { double alpha) throws IllegalArgumentException, MathException; /** - * Performs a + * Performs a * - * two-sided t-test evaluating the null hypothesis that sample1 - * and sample2 are drawn from populations with the same mean, + * two-sided t-test evaluating the null hypothesis that sample1 + * and sample2 are drawn from populations with the same mean, * with significance level alpha, assuming that the - * subpopulation variances are equal. Use + * subpopulation variances are equal. Use * {@link #tTest(double[], double[], double)} to perform the test without * the assumption of equal variances. *

    * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To + * equal can be rejected with confidence 1 - alpha. To * perform a 1-sided test, use alpha * 2. To perform the test - * without the assumption of equal subpopulation variances, use + * without the assumption of equal subpopulation variances, use * {@link #tTest(double[], double[], double)}.

    *

    * A pooled variance estimate is used to compute the t-statistic. See @@ -604,7 +604,7 @@ public interface TTest { * the 95% level, use
    tTest(sample1, sample2, 0.05). * *

  • To test the (one-sided) hypothesis mean 1 < mean 2, - * at the 99% level, first verify that the measured mean of + * at the 99% level, first verify that the measured mean of * sample 1 is less than the mean of sample 2 * and then use *
    tTest(sample1, sample2, 0.02) @@ -612,7 +612,7 @@ public interface TTest { *

    * Usage Note:
    * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

    *

    @@ -625,7 +625,7 @@ public interface TTest { * @param sample1 array of sample data values * @param sample2 array of sample data values * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if an error occurs performing the test @@ -636,25 +636,25 @@ public interface TTest { double alpha) throws IllegalArgumentException, MathException; /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a two-sample, two-tailed t-test * comparing the means of the datasets described by two StatisticalSummary * instances. *

    * The number returned is the smallest significance level * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. + * equal in favor of the two-sided alternative that they are different. * For a one-sided test, divide the returned value by 2.

    *

    * The test does not assume that the underlying popuation variances are - * equal and it uses approximated degrees of freedom computed from the + * equal and it uses approximated degrees of freedom computed from the * sample data to compute the p-value. To perform the test assuming - * equal variances, use + * equal variances, use * {@link #homoscedasticTTest(StatisticalSummary, StatisticalSummary)}.

    *

    * Usage Note:
    * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

    *

    @@ -674,8 +674,8 @@ public interface TTest { StatisticalSummary sampleStats2) throws IllegalArgumentException, MathException; /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a two-sample, two-tailed t-test * comparing the means of the datasets described by two StatisticalSummary * instances, under the hypothesis of equal subpopulation variances. To * perform a test without the equal variances assumption, use @@ -683,7 +683,7 @@ public interface TTest { *

    * The number returned is the smallest significance level * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. + * equal in favor of the two-sided alternative that they are different. * For a one-sided test, divide the returned value by 2.

    *

    * See {@link #homoscedasticT(double[], double[])} for the formula used to @@ -692,7 +692,7 @@ public interface TTest { *

    * Usage Note:
    * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * here *

    * Preconditions:

      @@ -711,9 +711,9 @@ public interface TTest { StatisticalSummary sampleStats2) throws IllegalArgumentException, MathException; /** - * Performs a + * Performs a * - * two-sided t-test evaluating the null hypothesis that + * two-sided t-test evaluating the null hypothesis that * sampleStats1 and sampleStats2 describe * datasets drawn from populations with the same mean, with significance * level alpha. This test does not assume that the @@ -722,7 +722,7 @@ public interface TTest { * {@link #homoscedasticTTest(StatisticalSummary, StatisticalSummary)}. *

      * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To + * equal can be rejected with confidence 1 - alpha. To * perform a 1-sided test, use alpha * 2

      *

      * See {@link #t(double[], double[])} for the formula used to compute the @@ -732,19 +732,19 @@ public interface TTest { *

      * Examples:

        *
      1. To test the (2-sided) hypothesis mean 1 = mean 2 at - * the 95%, use + * the 95%, use *
        tTest(sampleStats1, sampleStats2, 0.05) *
      2. *
      3. To test the (one-sided) hypothesis mean 1 < mean 2 - * at the 99% level, first verify that the measured mean of + * at the 99% level, first verify that the measured mean of * sample 1 is less than the mean of sample 2 - * and then use + * and then use *
        tTest(sampleStats1, sampleStats2, 0.02) *

      *

      * Usage Note:
      * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

      *

      @@ -758,7 +758,7 @@ public interface TTest { * @param sampleStats1 StatisticalSummary describing sample data values * @param sampleStats2 StatisticalSummary describing sample data values * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if an error occurs performing the test @@ -768,4 +768,4 @@ public interface TTest { StatisticalSummary sampleStats2, double alpha) throws IllegalArgumentException, MathException; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/math/stat/inference/TTestImpl.java b/src/main/java/org/apache/commons/math/stat/inference/TTestImpl.java index ab984ee23..64009bb05 100644 --- a/src/main/java/org/apache/commons/math/stat/inference/TTestImpl.java +++ b/src/main/java/org/apache/commons/math/stat/inference/TTestImpl.java @@ -35,14 +35,14 @@ public class TTestImpl implements TTest { /** Distribution used to compute inference statistics. */ private TDistribution distribution; - + /** * Default constructor. */ public TTestImpl() { this(new TDistributionImpl(1.0)); } - + /** * Create a test instance using the given distribution for computing * inference statistics. @@ -53,13 +53,13 @@ public class TTestImpl implements TTest { super(); setDistribution(t); } - + /** - * Computes a paired, 2-sample t-statistic based on the data in the input + * Computes a paired, 2-sample t-statistic based on the data in the input * arrays. The t-statistic returned is equivalent to what would be returned by * computing the one-sample t-statistic {@link #t(double, double[])}, with - * mu = 0 and the sample array consisting of the (signed) - * differences between corresponding entries in sample1 and + * mu = 0 and the sample array consisting of the (signed) + * differences between corresponding entries in sample1 and * sample2. *

      * Preconditions:

        @@ -79,30 +79,30 @@ public class TTestImpl implements TTest { checkSampleData(sample1); checkSampleData(sample2); double meanDifference = StatUtils.meanDifference(sample1, sample2); - return t(meanDifference, 0, + return t(meanDifference, 0, StatUtils.varianceDifference(sample1, sample2, meanDifference), sample1.length); } /** - * Returns the observed significance level, or - * p-value, associated with a paired, two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a paired, two-sample, two-tailed t-test * based on the data in the input arrays. *

        * The number returned is the smallest significance level * at which one can reject the null hypothesis that the mean of the paired - * differences is 0 in favor of the two-sided alternative that the mean paired - * difference is not equal to 0. For a one-sided test, divide the returned + * differences is 0 in favor of the two-sided alternative that the mean paired + * difference is not equal to 0. For a one-sided test, divide the returned * value by 2.

        *

        * This test is equivalent to a one-sample t-test computed using * {@link #tTest(double, double[])} with mu = 0 and the sample - * array consisting of the signed differences between corresponding elements of + * array consisting of the signed differences between corresponding elements of * sample1 and sample2.

        *

        * Usage Note:
        * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

        *

        @@ -120,30 +120,30 @@ public class TTestImpl implements TTest { public double pairedTTest(double[] sample1, double[] sample2) throws IllegalArgumentException, MathException { double meanDifference = StatUtils.meanDifference(sample1, sample2); - return tTest(meanDifference, 0, - StatUtils.varianceDifference(sample1, sample2, meanDifference), + return tTest(meanDifference, 0, + StatUtils.varianceDifference(sample1, sample2, meanDifference), sample1.length); } /** - * Performs a paired t-test evaluating the null hypothesis that the + * Performs a paired t-test evaluating the null hypothesis that the * mean of the paired differences between sample1 and - * sample2 is 0 in favor of the two-sided alternative that the - * mean paired difference is not equal to 0, with significance level + * sample2 is 0 in favor of the two-sided alternative that the + * mean paired difference is not equal to 0, with significance level * alpha. *

        - * Returns true iff the null hypothesis can be rejected with - * confidence 1 - alpha. To perform a 1-sided test, use + * Returns true iff the null hypothesis can be rejected with + * confidence 1 - alpha. To perform a 1-sided test, use * alpha * 2

        *

        * Usage Note:
        * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

        *

        * Preconditions:

          - *
        • The input array lengths must be the same and their common length + *
        • The input array lengths must be the same and their common length * must be at least 2. *
        • *
        • 0 < alpha < 0.5 @@ -152,7 +152,7 @@ public class TTestImpl implements TTest { * @param sample1 array of sample data values * @param sample2 array of sample data values * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if an error occurs performing the test @@ -164,7 +164,7 @@ public class TTestImpl implements TTest { } /** - * Computes a + * Computes a * t statistic given observed values and a comparison constant. *

          * This statistic can be used to perform a one sample t-test for the mean. @@ -187,7 +187,7 @@ public class TTestImpl implements TTest { /** * Computes a - * t statistic to use in comparing the mean of the dataset described by + * t statistic to use in comparing the mean of the dataset described by * sampleStats to mu. *

          * This statistic can be used to perform a one sample t-test for the mean. @@ -209,7 +209,7 @@ public class TTestImpl implements TTest { } /** - * Computes a 2-sample t statistic, under the hypothesis of equal + * Computes a 2-sample t statistic, under the hypothesis of equal * subpopulation variances. To compute a t-statistic without the * equal variances hypothesis, use {@link #t(double[], double[])}. *

          @@ -220,15 +220,15 @@ public class TTestImpl implements TTest { *

          *    t = (m1 - m2) / (sqrt(1/n1 +1/n2) sqrt(var)) *

          - * where n1 is the size of first sample; - * n2 is the size of second sample; - * m1 is the mean of first sample; + * where n1 is the size of first sample; + * n2 is the size of second sample; + * m1 is the mean of first sample; * m2 is the mean of second sample

        • *
        * and var is the pooled variance estimate: *

        * var = sqrt(((n1 - 1)var1 + (n2 - 1)var2) / ((n1-1) + (n2-1))) - *

        + *

        * with var1 the variance of the first sample and * var2 the variance of the second sample. *

        @@ -249,7 +249,7 @@ public class TTestImpl implements TTest { StatUtils.variance(sample1), StatUtils.variance(sample2), sample1.length, sample2.length); } - + /** * Computes a 2-sample t statistic, without the hypothesis of equal * subpopulation variances. To compute a t-statistic assuming equal @@ -263,11 +263,11 @@ public class TTestImpl implements TTest { *    t = (m1 - m2) / sqrt(var1/n1 + var2/n2) *

        * where n1 is the size of the first sample - * n2 is the size of the second sample; - * m1 is the mean of the first sample; + * n2 is the size of the second sample; + * m1 is the mean of the first sample; * m2 is the mean of the second sample; * var1 is the variance of the first sample; - * var2 is the variance of the second sample; + * var2 is the variance of the second sample; *

        * Preconditions:

          *
        • The observed array lengths must both be at least 2. @@ -290,7 +290,7 @@ public class TTestImpl implements TTest { /** * Computes a 2-sample t statistic , comparing the means of the datasets * described by two {@link StatisticalSummary} instances, without the - * assumption of equal subpopulation variances. Use + * assumption of equal subpopulation variances. Use * {@link #homoscedasticT(StatisticalSummary, StatisticalSummary)} to * compute a t-statistic under the equal variances assumption. *

          @@ -301,11 +301,11 @@ public class TTestImpl implements TTest { *

          *    t = (m1 - m2) / sqrt(var1/n1 + var2/n2) *

          - * where n1 is the size of the first sample; - * n2 is the size of the second sample; - * m1 is the mean of the first sample; + * where n1 is the size of the first sample; + * n2 is the size of the second sample; + * m1 is the mean of the first sample; * m2 is the mean of the second sample - * var1 is the variance of the first sample; + * var1 is the variance of the first sample; * var2 is the variance of the second sample *

          * Preconditions:

            @@ -318,21 +318,21 @@ public class TTestImpl implements TTest { * @return t statistic * @throws IllegalArgumentException if the precondition is not met */ - public double t(StatisticalSummary sampleStats1, + public double t(StatisticalSummary sampleStats1, StatisticalSummary sampleStats2) throws IllegalArgumentException { checkSampleData(sampleStats1); checkSampleData(sampleStats2); - return t(sampleStats1.getMean(), sampleStats2.getMean(), + return t(sampleStats1.getMean(), sampleStats2.getMean(), sampleStats1.getVariance(), sampleStats2.getVariance(), sampleStats1.getN(), sampleStats2.getN()); } - + /** * Computes a 2-sample t statistic, comparing the means of the datasets * described by two {@link StatisticalSummary} instances, under the * assumption of equal subpopulation variances. To compute a t-statistic - * without the equal variances assumption, use + * without the equal variances assumption, use * {@link #t(StatisticalSummary, StatisticalSummary)}. *

            * This statistic can be used to perform a (homoscedastic) two-sample @@ -342,14 +342,14 @@ public class TTestImpl implements TTest { *

            *    t = (m1 - m2) / (sqrt(1/n1 +1/n2) sqrt(var)) *

            - * where n1 is the size of first sample; - * n2 is the size of second sample; - * m1 is the mean of first sample; + * where n1 is the size of first sample; + * n2 is the size of second sample; + * m1 is the mean of first sample; * m2 is the mean of second sample * and var is the pooled variance estimate: *

            * var = sqrt(((n1 - 1)var1 + (n2 - 1)var2) / ((n1-1) + (n2-1))) - *

            + *

            * with var1 the variance of the first sample and * var2 the variance of the second sample. *

            @@ -363,30 +363,30 @@ public class TTestImpl implements TTest { * @return t statistic * @throws IllegalArgumentException if the precondition is not met */ - public double homoscedasticT(StatisticalSummary sampleStats1, + public double homoscedasticT(StatisticalSummary sampleStats1, StatisticalSummary sampleStats2) throws IllegalArgumentException { checkSampleData(sampleStats1); checkSampleData(sampleStats2); - return homoscedasticT(sampleStats1.getMean(), sampleStats2.getMean(), - sampleStats1.getVariance(), sampleStats2.getVariance(), + return homoscedasticT(sampleStats1.getMean(), sampleStats2.getMean(), + sampleStats1.getVariance(), sampleStats2.getVariance(), sampleStats1.getN(), sampleStats2.getN()); } /** - * Returns the observed significance level, or - * p-value, associated with a one-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a one-sample, two-tailed t-test * comparing the mean of the input array with the constant mu. *

            * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the mean equals + * at which one can reject the null hypothesis that the mean equals * mu in favor of the two-sided alternative that the mean - * is different from mu. For a one-sided test, divide the + * is different from mu. For a one-sided test, divide the * returned value by 2.

            *

            * Usage Note:
            * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * here *

            * Preconditions:

              @@ -411,8 +411,8 @@ public class TTestImpl implements TTest { * two-sided t-test evaluating the null hypothesis that the mean of the population from * which sample is drawn equals mu. *

              - * Returns true iff the null hypothesis can be - * rejected with confidence 1 - alpha. To + * Returns true iff the null hypothesis can be + * rejected with confidence 1 - alpha. To * perform a 1-sided test, use alpha * 2 *

              * Examples:

                @@ -420,14 +420,14 @@ public class TTestImpl implements TTest { * the 95% level, use
                tTest(mu, sample, 0.05) * *
              1. To test the (one-sided) hypothesis sample mean < mu - * at the 99% level, first verify that the measured sample mean is less - * than mu and then use + * at the 99% level, first verify that the measured sample mean is less + * than mu and then use *
                tTest(mu, sample, 0.02) *

              *

              * Usage Note:
              - * The validity of the test depends on the assumptions of the one-sample - * parametric t-test procedure, as discussed + * The validity of the test depends on the assumptions of the one-sample + * parametric t-test procedure, as discussed * here *

              * Preconditions:

                @@ -448,20 +448,20 @@ public class TTestImpl implements TTest { } /** - * Returns the observed significance level, or - * p-value, associated with a one-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a one-sample, two-tailed t-test * comparing the mean of the dataset described by sampleStats * with the constant mu. *

                * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the mean equals + * at which one can reject the null hypothesis that the mean equals * mu in favor of the two-sided alternative that the mean - * is different from mu. For a one-sided test, divide the + * is different from mu. For a one-sided test, divide the * returned value by 2.

                *

                * Usage Note:
                * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

                *

                @@ -497,14 +497,14 @@ public class TTestImpl implements TTest { * the 95% level, use
                tTest(mu, sampleStats, 0.05) * *

              • To test the (one-sided) hypothesis sample mean < mu - * at the 99% level, first verify that the measured sample mean is less - * than mu and then use + * at the 99% level, first verify that the measured sample mean is less + * than mu and then use *
                tTest(mu, sampleStats, 0.02) *
              • *

                * Usage Note:
                - * The validity of the test depends on the assumptions of the one-sample - * parametric t-test procedure, as discussed + * The validity of the test depends on the assumptions of the one-sample + * parametric t-test procedure, as discussed * here *

                * Preconditions:

                  @@ -526,28 +526,28 @@ public class TTestImpl implements TTest { } /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a two-sample, two-tailed t-test * comparing the means of the input arrays. *

                  * The number returned is the smallest significance level * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. + * equal in favor of the two-sided alternative that they are different. * For a one-sided test, divide the returned value by 2.

                  *

                  * The test does not assume that the underlying popuation variances are - * equal and it uses approximated degrees of freedom computed from the + * equal and it uses approximated degrees of freedom computed from the * sample data to compute the p-value. The t-statistic used is as defined in * {@link #t(double[], double[])} and the Welch-Satterthwaite approximation - * to the degrees of freedom is used, - * as described + * to the degrees of freedom is used, + * as described * * here. To perform the test under the assumption of equal subpopulation * variances, use {@link #homoscedasticTTest(double[], double[])}.

                  *

                  * Usage Note:
                  * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

                  *

                  @@ -569,10 +569,10 @@ public class TTestImpl implements TTest { StatUtils.variance(sample1), StatUtils.variance(sample2), sample1.length, sample2.length); } - + /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a two-sample, two-tailed t-test * comparing the means of the input arrays, under the assumption that * the two samples are drawn from subpopulations with equal variances. * To perform the test without the equal variances assumption, use @@ -580,7 +580,7 @@ public class TTestImpl implements TTest { *

                  * The number returned is the smallest significance level * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. + * equal in favor of the two-sided alternative that they are different. * For a one-sided test, divide the returned value by 2.

                  *

                  * A pooled variance estimate is used to compute the t-statistic. See @@ -589,7 +589,7 @@ public class TTestImpl implements TTest { *

                  * Usage Note:
                  * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

                  *

                  @@ -607,47 +607,47 @@ public class TTestImpl implements TTest { throws IllegalArgumentException, MathException { checkSampleData(sample1); checkSampleData(sample2); - return homoscedasticTTest(StatUtils.mean(sample1), + return homoscedasticTTest(StatUtils.mean(sample1), StatUtils.mean(sample2), StatUtils.variance(sample1), - StatUtils.variance(sample2), sample1.length, + StatUtils.variance(sample2), sample1.length, sample2.length); } - + /** - * Performs a + * Performs a * - * two-sided t-test evaluating the null hypothesis that sample1 - * and sample2 are drawn from populations with the same mean, + * two-sided t-test evaluating the null hypothesis that sample1 + * and sample2 are drawn from populations with the same mean, * with significance level alpha. This test does not assume * that the subpopulation variances are equal. To perform the test assuming - * equal variances, use + * equal variances, use * {@link #homoscedasticTTest(double[], double[], double)}. *

                  * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To + * equal can be rejected with confidence 1 - alpha. To * perform a 1-sided test, use alpha / 2

                  *

                  * See {@link #t(double[], double[])} for the formula used to compute the * t-statistic. Degrees of freedom are approximated using the * * Welch-Satterthwaite approximation.

                  - + *

                  * Examples:

                    *
                  1. To test the (2-sided) hypothesis mean 1 = mean 2 at - * the 95% level, use + * the 95% level, use *
                    tTest(sample1, sample2, 0.05). *
                  2. *
                  3. To test the (one-sided) hypothesis mean 1 < mean 2 at * the 99% level, first verify that the measured mean of sample 1 - * is less than the mean of sample 2 and then use + * is less than the mean of sample 2 and then use *
                    tTest(sample1, sample2, 0.02) *

                  *

                  * Usage Note:
                  * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

                  *

                  @@ -660,7 +660,7 @@ public class TTestImpl implements TTest { * @param sample1 array of sample data values * @param sample2 array of sample data values * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if an error occurs performing the test @@ -671,21 +671,21 @@ public class TTestImpl implements TTest { checkSignificanceLevel(alpha); return (tTest(sample1, sample2) < alpha); } - + /** - * Performs a + * Performs a * - * two-sided t-test evaluating the null hypothesis that sample1 - * and sample2 are drawn from populations with the same mean, + * two-sided t-test evaluating the null hypothesis that sample1 + * and sample2 are drawn from populations with the same mean, * with significance level alpha, assuming that the - * subpopulation variances are equal. Use + * subpopulation variances are equal. Use * {@link #tTest(double[], double[], double)} to perform the test without * the assumption of equal variances. *

                  * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To + * equal can be rejected with confidence 1 - alpha. To * perform a 1-sided test, use alpha * 2. To perform the test - * without the assumption of equal subpopulation variances, use + * without the assumption of equal subpopulation variances, use * {@link #tTest(double[], double[], double)}.

                  *

                  * A pooled variance estimate is used to compute the t-statistic. See @@ -697,7 +697,7 @@ public class TTestImpl implements TTest { * the 95% level, use
                  tTest(sample1, sample2, 0.05). * *

                • To test the (one-sided) hypothesis mean 1 < mean 2, - * at the 99% level, first verify that the measured mean of + * at the 99% level, first verify that the measured mean of * sample 1 is less than the mean of sample 2 * and then use *
                  tTest(sample1, sample2, 0.02) @@ -705,7 +705,7 @@ public class TTestImpl implements TTest { *

                  * Usage Note:
                  * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

                  *

                  @@ -718,7 +718,7 @@ public class TTestImpl implements TTest { * @param sample1 array of sample data values * @param sample2 array of sample data values * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if an error occurs performing the test @@ -731,25 +731,25 @@ public class TTestImpl implements TTest { } /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a two-sample, two-tailed t-test * comparing the means of the datasets described by two StatisticalSummary * instances. *

                  * The number returned is the smallest significance level * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. + * equal in favor of the two-sided alternative that they are different. * For a one-sided test, divide the returned value by 2.

                  *

                  * The test does not assume that the underlying popuation variances are - * equal and it uses approximated degrees of freedom computed from the + * equal and it uses approximated degrees of freedom computed from the * sample data to compute the p-value. To perform the test assuming - * equal variances, use + * equal variances, use * {@link #homoscedasticTTest(StatisticalSummary, StatisticalSummary)}.

                  *

                  * Usage Note:
                  * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

                  *

                  @@ -769,13 +769,13 @@ public class TTestImpl implements TTest { checkSampleData(sampleStats1); checkSampleData(sampleStats2); return tTest(sampleStats1.getMean(), sampleStats2.getMean(), sampleStats1.getVariance(), - sampleStats2.getVariance(), sampleStats1.getN(), + sampleStats2.getVariance(), sampleStats1.getN(), sampleStats2.getN()); } - + /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test + * Returns the observed significance level, or + * p-value, associated with a two-sample, two-tailed t-test * comparing the means of the datasets described by two StatisticalSummary * instances, under the hypothesis of equal subpopulation variances. To * perform a test without the equal variances assumption, use @@ -783,7 +783,7 @@ public class TTestImpl implements TTest { *

                  * The number returned is the smallest significance level * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. + * equal in favor of the two-sided alternative that they are different. * For a one-sided test, divide the returned value by 2.

                  *

                  * See {@link #homoscedasticT(double[], double[])} for the formula used to @@ -792,7 +792,7 @@ public class TTestImpl implements TTest { *

                  * Usage Note:
                  * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * here *

                  * Preconditions:

                    @@ -806,21 +806,21 @@ public class TTestImpl implements TTest { * @throws IllegalArgumentException if the precondition is not met * @throws MathException if an error occurs computing the p-value */ - public double homoscedasticTTest(StatisticalSummary sampleStats1, + public double homoscedasticTTest(StatisticalSummary sampleStats1, StatisticalSummary sampleStats2) throws IllegalArgumentException, MathException { checkSampleData(sampleStats1); checkSampleData(sampleStats2); return homoscedasticTTest(sampleStats1.getMean(), sampleStats2.getMean(), sampleStats1.getVariance(), - sampleStats2.getVariance(), sampleStats1.getN(), + sampleStats2.getVariance(), sampleStats1.getN(), sampleStats2.getN()); } /** - * Performs a + * Performs a * - * two-sided t-test evaluating the null hypothesis that + * two-sided t-test evaluating the null hypothesis that * sampleStats1 and sampleStats2 describe * datasets drawn from populations with the same mean, with significance * level alpha. This test does not assume that the @@ -829,7 +829,7 @@ public class TTestImpl implements TTest { * {@link #homoscedasticTTest(StatisticalSummary, StatisticalSummary)}. *

                    * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To + * equal can be rejected with confidence 1 - alpha. To * perform a 1-sided test, use alpha * 2

                    *

                    * See {@link #t(double[], double[])} for the formula used to compute the @@ -839,19 +839,19 @@ public class TTestImpl implements TTest { *

                    * Examples:

                      *
                    1. To test the (2-sided) hypothesis mean 1 = mean 2 at - * the 95%, use + * the 95%, use *
                      tTest(sampleStats1, sampleStats2, 0.05) *
                    2. *
                    3. To test the (one-sided) hypothesis mean 1 < mean 2 - * at the 99% level, first verify that the measured mean of + * at the 99% level, first verify that the measured mean of * sample 1 is less than the mean of sample 2 - * and then use + * and then use *
                      tTest(sampleStats1, sampleStats2, 0.02) *

                    *

                    * Usage Note:
                    * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed + * t-test procedure, as discussed * * here

                    *

                    @@ -865,7 +865,7 @@ public class TTestImpl implements TTest { * @param sampleStats1 StatisticalSummary describing sample data values * @param sampleStats2 StatisticalSummary describing sample data values * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with + * @return true if the null hypothesis can be rejected with * confidence 1 - alpha * @throws IllegalArgumentException if the preconditions are not met * @throws MathException if an error occurs performing the test @@ -876,12 +876,12 @@ public class TTestImpl implements TTest { checkSignificanceLevel(alpha); return (tTest(sampleStats1, sampleStats2) < alpha); } - - //----------------------------------------------- Protected methods + + //----------------------------------------------- Protected methods /** * Computes approximate degrees of freedom for 2-sample t-test. - * + * * @param v1 first sample variance * @param v2 second sample variance * @param n1 first sample n @@ -896,7 +896,7 @@ public class TTestImpl implements TTest { /** * Computes t test statistic for 1-sample t-test. - * + * * @param m sample mean * @param mu constant to test against * @param v sample variance @@ -906,12 +906,12 @@ public class TTestImpl implements TTest { protected double t(double m, double mu, double v, double n) { return (m - mu) / Math.sqrt(v / n); } - + /** * Computes t test statistic for 2-sample t-test. *

                    * Does not assume that subpopulation variances are equal.

                    - * + * * @param m1 first sample mean * @param m2 second sample mean * @param v1 first sample variance @@ -924,11 +924,11 @@ public class TTestImpl implements TTest { double n2) { return (m1 - m2) / Math.sqrt((v1 / n1) + (v2 / n2)); } - + /** * Computes t test statistic for 2-sample t-test under the hypothesis * of equal subpopulation variances. - * + * * @param m1 first sample mean * @param m2 second sample mean * @param v1 first sample variance @@ -939,13 +939,13 @@ public class TTestImpl implements TTest { */ protected double homoscedasticT(double m1, double m2, double v1, double v2, double n1, double n2) { - double pooledVariance = ((n1 - 1) * v1 + (n2 -1) * v2 ) / (n1 + n2 - 2); + double pooledVariance = ((n1 - 1) * v1 + (n2 -1) * v2 ) / (n1 + n2 - 2); return (m1 - m2) / Math.sqrt(pooledVariance * (1d / n1 + 1d / n2)); } - + /** * Computes p-value for 2-sided, 1-sample t-test. - * + * * @param m sample mean * @param mu constant to test against * @param v sample variance @@ -965,7 +965,7 @@ public class TTestImpl implements TTest { *

                    * Does not assume subpopulation variances are equal. Degrees of freedom * are estimated from the data.

                    - * + * * @param m1 first sample mean * @param m2 second sample mean * @param v1 first sample variance @@ -975,7 +975,7 @@ public class TTestImpl implements TTest { * @return p-value * @throws MathException if an error occurs computing the p-value */ - protected double tTest(double m1, double m2, double v1, double v2, + protected double tTest(double m1, double m2, double v1, double v2, double n1, double n2) throws MathException { double t = Math.abs(t(m1, m2, v1, v2, n1, n2)); @@ -984,13 +984,13 @@ public class TTestImpl implements TTest { distribution.setDegreesOfFreedom(degreesOfFreedom); return 2.0 * distribution.cumulativeProbability(-t); } - + /** * Computes p-value for 2-sided, 2-sample t-test, under the assumption * of equal subpopulation variances. *

                    * The sum of the sample sizes minus 2 is used as degrees of freedom.

                    - * + * * @param m1 first sample mean * @param m2 second sample mean * @param v1 first sample variance @@ -1008,7 +1008,7 @@ public class TTestImpl implements TTest { distribution.setDegreesOfFreedom(degreesOfFreedom); return 2.0 * distribution.cumulativeProbability(-t); } - + /** * Modify the distribution used to compute inference statistics. * @param value the new distribution diff --git a/src/main/java/org/apache/commons/math/stat/inference/TestUtils.java b/src/main/java/org/apache/commons/math/stat/inference/TestUtils.java index 468acd214..1921a459a 100644 --- a/src/main/java/org/apache/commons/math/stat/inference/TestUtils.java +++ b/src/main/java/org/apache/commons/math/stat/inference/TestUtils.java @@ -25,7 +25,7 @@ import org.apache.commons.math.stat.descriptive.StatisticalSummary; * perform inference tests. * * @since 1.1 - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public class TestUtils { /** @@ -34,100 +34,100 @@ public class TestUtils { protected TestUtils() { super(); } - + /** Singleton TTest instance using default implementation. */ private static TTest tTest = new TTestImpl(); - + /** Singleton ChiSquareTest instance using default implementation. */ - private static ChiSquareTest chiSquareTest = + private static ChiSquareTest chiSquareTest = new ChiSquareTestImpl(); - + /** Singleton ChiSquareTest instance using default implementation. */ - private static UnknownDistributionChiSquareTest unknownDistributionChiSquareTest = + private static UnknownDistributionChiSquareTest unknownDistributionChiSquareTest = new ChiSquareTestImpl(); - + /** Singleton OneWayAnova instance using default implementation. */ private static OneWayAnova oneWayAnova = new OneWayAnovaImpl(); - + /** * Set the (singleton) TTest instance. - * + * * @param chiSquareTest the new instance to use * @since 1.2 */ public static void setChiSquareTest(TTest chiSquareTest) { TestUtils.tTest = chiSquareTest; } - + /** * Return a (singleton) TTest instance. Does not create a new instance. - * + * * @return a TTest instance */ public static TTest getTTest() { return tTest; } - + /** * Set the (singleton) ChiSquareTest instance. - * + * * @param chiSquareTest the new instance to use * @since 1.2 */ public static void setChiSquareTest(ChiSquareTest chiSquareTest) { TestUtils.chiSquareTest = chiSquareTest; } - + /** * Return a (singleton) ChiSquareTest instance. Does not create a new instance. - * + * * @return a ChiSquareTest instance */ public static ChiSquareTest getChiSquareTest() { return chiSquareTest; } - + /** * Set the (singleton) UnknownDistributionChiSquareTest instance. - * + * * @param unknownDistributionChiSquareTest the new instance to use * @since 1.2 */ public static void setUnknownDistributionChiSquareTest(UnknownDistributionChiSquareTest unknownDistributionChiSquareTest) { TestUtils.unknownDistributionChiSquareTest = unknownDistributionChiSquareTest; } - + /** * Return a (singleton) UnknownDistributionChiSquareTest instance. Does not create a new instance. - * + * * @return a UnknownDistributionChiSquareTest instance */ public static UnknownDistributionChiSquareTest getUnknownDistributionChiSquareTest() { return unknownDistributionChiSquareTest; } - + /** * Set the (singleton) OneWayAnova instance - * + * * @param oneWayAnova the new instance to use * @since 1.2 */ public static void setOneWayAnova(OneWayAnova oneWayAnova) { TestUtils.oneWayAnova = oneWayAnova; } - + /** * Return a (singleton) OneWayAnova instance. Does not create a new instance. - * + * * @return a OneWayAnova instance * @since 1.2 */ public static OneWayAnova getOneWayAnova() { return oneWayAnova; } - - + + // CHECKSTYLE: stop JavadocMethodCheck /** @@ -309,7 +309,7 @@ public class TestUtils { /** * @see org.apache.commons.math.stat.inference.ChiSquareTest#chiSquare(long[][]) */ - public static double chiSquare(long[][] counts) + public static double chiSquare(long[][] counts) throws IllegalArgumentException { return chiSquareTest.chiSquare(counts); } @@ -378,7 +378,7 @@ public class TestUtils { throws IllegalArgumentException, MathException { return unknownDistributionChiSquareTest.chiSquareTestDataSetsComparison(observed1, observed2, alpha); } - + /** * @see org.apache.commons.math.stat.inference.OneWayAnova#anovaFValue(Collection) * @@ -388,17 +388,17 @@ public class TestUtils { throws IllegalArgumentException, MathException { return oneWayAnova.anovaFValue(categoryData); } - + /** * @see org.apache.commons.math.stat.inference.OneWayAnova#anovaPValue(Collection) - * + * * @since 1.2 */ public static double oneWayAnovaPValue(Collection categoryData) throws IllegalArgumentException, MathException { return oneWayAnova.anovaPValue(categoryData); } - + /** * @see org.apache.commons.math.stat.inference.OneWayAnova#anovaTest(Collection,double) * diff --git a/src/main/java/org/apache/commons/math/stat/inference/UnknownDistributionChiSquareTest.java b/src/main/java/org/apache/commons/math/stat/inference/UnknownDistributionChiSquareTest.java index db4a62edf..5f644556c 100644 --- a/src/main/java/org/apache/commons/math/stat/inference/UnknownDistributionChiSquareTest.java +++ b/src/main/java/org/apache/commons/math/stat/inference/UnknownDistributionChiSquareTest.java @@ -24,12 +24,12 @@ import org.apache.commons.math.MathException; * but provided by one sample. We compare the second sample against the first.

                    * * @version $Revision$ $Date$ - * @since 1.2 + * @since 1.2 */ public interface UnknownDistributionChiSquareTest extends ChiSquareTest { - + /** - *

                    Computes a + *

                    Computes a * * Chi-Square two sample test statistic comparing bin frequency counts * in observed1 and observed2. The @@ -37,7 +37,7 @@ public interface UnknownDistributionChiSquareTest extends ChiSquareTest { * same. The formula used to compute the test statistic is

                    * * ∑[(K * observed1[i] - observed2[i]/K)2 / (observed1[i] + observed2[i])] - * where + *
                    where *
                    K = &sqrt;[&sum(observed2 / ∑(observed1)] *

                    *

                    This statistic can be used to perform a Chi-Square test evaluating the null hypothesis that @@ -68,7 +68,7 @@ public interface UnknownDistributionChiSquareTest extends ChiSquareTest { *

                    Returns the observed significance level, or * p-value, associated with a Chi-Square two sample test comparing - * bin frequency counts in observed1 and + * bin frequency counts in observed1 and * observed2. *

                    *

                    The number returned is the smallest significance level at which one @@ -110,7 +110,7 @@ public interface UnknownDistributionChiSquareTest extends ChiSquareTest { * significance level alpha. Returns true iff the null * hypothesis can be rejected with 100 * (1 - alpha) percent confidence. *

                    - *

                    See {@link #chiSquareDataSetsComparison(long[], long[])} for + *

                    See {@link #chiSquareDataSetsComparison(long[], long[])} for * details on the formula used to compute the Chisquare statistic used * in the test. The degrees of of freedom used to perform the test is * one less than the common length of the input observed count arrays. diff --git a/src/main/java/org/apache/commons/math/stat/ranking/NaNStrategy.java b/src/main/java/org/apache/commons/math/stat/ranking/NaNStrategy.java index 5fa0f1709..c7508fdae 100644 --- a/src/main/java/org/apache/commons/math/stat/ranking/NaNStrategy.java +++ b/src/main/java/org/apache/commons/math/stat/ranking/NaNStrategy.java @@ -34,16 +34,16 @@ package org.apache.commons.math.stat.ranking; * @version $Revision$ $Date$ */ public enum NaNStrategy { - + /** NaNs are considered minimal in the ordering */ MINIMAL, - + /** NaNs are considered maximal in the ordering */ MAXIMAL, - + /** NaNs are removed before computing ranks */ REMOVED, - + /** NaNs are left in place */ FIXED } diff --git a/src/main/java/org/apache/commons/math/stat/ranking/NaturalRanking.java b/src/main/java/org/apache/commons/math/stat/ranking/NaturalRanking.java index 4f852c5cd..50f5a4f93 100644 --- a/src/main/java/org/apache/commons/math/stat/ranking/NaturalRanking.java +++ b/src/main/java/org/apache/commons/math/stat/ranking/NaturalRanking.java @@ -31,10 +31,10 @@ import org.apache.commons.math.random.RandomGenerator; /** *

                    Ranking based on the natural ordering on doubles.

                    *

                    NaNs are treated according to the configured {@link NaNStrategy} and ties - * are handled using the selected {@link TiesStrategy}. + * are handled using the selected {@link TiesStrategy}. * Configuration settings are supplied in optional constructor arguments. * Defaults are {@link NaNStrategy#MAXIMAL} and {@link TiesStrategy#AVERAGE}, - * respectively. When using {@link TiesStrategy#RANDOM}, a + * respectively. When using {@link TiesStrategy#RANDOM}, a * {@link RandomGenerator} may be supplied as a constructor argument.

                    *

                    Examples: * @@ -63,27 +63,27 @@ import org.apache.commons.math.random.RandomGenerator; * * *
                    MINIMALMAXIMUM(6, 5, 7, 8, 5, 9, 2, 2, 5)

                    - * + * * @since 2.0 * @version $Revision$ $Date$ */ public class NaturalRanking implements RankingAlgorithm { - + /** NaN strategy - defaults to NaNs maximal */ private final NaNStrategy nanStrategy; - + /** Ties strategy - defaults to ties averaged */ private final TiesStrategy tiesStrategy; - + /** Source of random data - used only when ties strategy is RANDOM */ private final RandomData randomData; - + /** default NaN strategy */ public static final NaNStrategy DEFAULT_NAN_STRATEGY = NaNStrategy.MAXIMAL; - + /** default ties strategy */ public static final TiesStrategy DEFAULT_TIES_STRATEGY = TiesStrategy.AVERAGE; - + /** * Create a NaturalRanking with default strategies for handling ties and NaNs. */ @@ -96,7 +96,7 @@ public class NaturalRanking implements RankingAlgorithm { /** * Create a NaturalRanking with the given TiesStrategy. - * + * * @param tiesStrategy the TiesStrategy to use */ public NaturalRanking(TiesStrategy tiesStrategy) { @@ -108,19 +108,19 @@ public class NaturalRanking implements RankingAlgorithm { /** * Create a NaturalRanking with the given NaNStrategy. - * + * * @param nanStrategy the NaNStrategy to use */ public NaturalRanking(NaNStrategy nanStrategy) { super(); this.nanStrategy = nanStrategy; tiesStrategy = DEFAULT_TIES_STRATEGY; - randomData = null; + randomData = null; } /** * Create a NaturalRanking with the given NaNStrategy and TiesStrategy. - * + * * @param nanStrategy NaNStrategy to use * @param tiesStrategy TiesStrategy to use */ @@ -130,11 +130,11 @@ public class NaturalRanking implements RankingAlgorithm { this.tiesStrategy = tiesStrategy; randomData = new RandomDataImpl(); } - + /** * Create a NaturalRanking with TiesStrategy.RANDOM and the given * RandomGenerator as the source of random data. - * + * * @param randomGenerator source of random data */ public NaturalRanking(RandomGenerator randomGenerator) { @@ -148,7 +148,7 @@ public class NaturalRanking implements RankingAlgorithm { /** * Create a NaturalRanking with the given NaNStrategy, TiesStrategy.RANDOM * and the given source of random data. - * + * * @param nanStrategy NaNStrategy to use * @param randomGenerator source of random data */ @@ -159,10 +159,10 @@ public class NaturalRanking implements RankingAlgorithm { this.tiesStrategy = TiesStrategy.RANDOM; randomData = new RandomDataImpl(randomGenerator); } - + /** * Return the NaNStrategy - * + * * @return returns the NaNStrategy */ public NaNStrategy getNanStrategy() { @@ -171,7 +171,7 @@ public class NaturalRanking implements RankingAlgorithm { /** * Return the TiesStrategy - * + * * @return the TiesStrategy */ public TiesStrategy getTiesStrategy() { @@ -182,18 +182,18 @@ public class NaturalRanking implements RankingAlgorithm { * Rank data using the natural ordering on Doubles, with * NaN values handled according to nanStrategy and ties * resolved using tiesStrategy. - * + * * @param data array to be ranked * @return array of ranks */ public double[] rank(double[] data) { - + // Array recording initial positions of data to be ranked - IntDoublePair[] ranks = new IntDoublePair[data.length]; + IntDoublePair[] ranks = new IntDoublePair[data.length]; for (int i = 0; i < data.length; i++) { ranks[i] = new IntDoublePair(data[i], i); } - + // Recode, remove or record positions of NaNs List nanPositions = null; switch (nanStrategy) { @@ -212,14 +212,14 @@ public class NaturalRanking implements RankingAlgorithm { default: // this should not happen unless NaNStrategy enum is changed throw MathRuntimeException.createInternalError(null); } - + // Sort the IntDoublePairs Arrays.sort(ranks); - + // Walk the sorted array, filling output array using sorted positions, // resolving ties as we go double[] out = new double[ranks.length]; - int pos = 1; // position in sorted array + int pos = 1; // position in sorted array out[ranks[0].getPosition()] = pos; List tiesTrace = new ArrayList(); tiesTrace.add(ranks[0].getPosition()); @@ -246,11 +246,11 @@ public class NaturalRanking implements RankingAlgorithm { } return out; } - + /** * Returns an array that is a copy of the input array with IntDoublePairs * having NaN values removed. - * + * * @param ranks input array * @return array with NaN-valued entries removed */ @@ -279,8 +279,8 @@ public class NaturalRanking implements RankingAlgorithm { } /** - * Recodes NaN values to the given value. - * + * Recodes NaN values to the given value. + * * @param ranks array to recode * @param value the value to replace NaNs with */ @@ -292,10 +292,10 @@ public class NaturalRanking implements RankingAlgorithm { } } } - + /** * Checks for presence of NaNs in ranks. - * + * * @param ranks array to be searched for NaNs * @return true iff ranks contains one or more NaNs */ @@ -307,7 +307,7 @@ public class NaturalRanking implements RankingAlgorithm { } return false; } - + /** * Resolve a sequence of ties, using the configured {@link TiesStrategy}. * The input ranks array is expected to take the same value @@ -316,20 +316,20 @@ public class NaturalRanking implements RankingAlgorithm { * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged. * The same array and trace with tiesStrategy AVERAGE will come out * <5,8,3,6,3,7,1,3>. - * - * @param ranks array of ranks + * + * @param ranks array of ranks * @param tiesTrace list of indices where ranks is constant - * -- that is, for any i and j in TiesTrace, ranks[i] == ranks[j] + * -- that is, for any i and j in TiesTrace, ranks[i] == ranks[j] * */ private void resolveTie(double[] ranks, List tiesTrace) { - + // constant value of ranks over tiesTrace final double c = ranks[tiesTrace.get(0)]; - + // length of sequence of tied ranks final int length = tiesTrace.size(); - + switch (tiesStrategy) { case AVERAGE: // Replace ranks with average fill(ranks, tiesTrace, (2 * c + length - 1) / 2d); @@ -344,7 +344,7 @@ public class NaturalRanking implements RankingAlgorithm { Iterator iterator = tiesTrace.iterator(); long f = Math.round(c); while (iterator.hasNext()) { - ranks[iterator.next()] = + ranks[iterator.next()] = randomData.nextLong(f, f + length - 1); } break; @@ -359,12 +359,12 @@ public class NaturalRanking implements RankingAlgorithm { break; default: // this should not happen unless TiesStrategy enum is changed throw MathRuntimeException.createInternalError(null); - } + } } - + /** * Setsdata[i] = value for each i in tiesTrace. - * + * * @param data array to modify * @param tiesTrace list of index values to set * @param value value to set @@ -375,10 +375,10 @@ public class NaturalRanking implements RankingAlgorithm { data[iterator.next()] = value; } } - + /** * Set ranks[i] = Double.NaN for each i in nanPositions. - * + * * @param ranks array to modify * @param nanPositions list of index values to set to Double.NaN */ @@ -388,14 +388,14 @@ public class NaturalRanking implements RankingAlgorithm { } Iterator iterator = nanPositions.iterator(); while (iterator.hasNext()) { - ranks[iterator.next().intValue()] = Double.NaN; + ranks[iterator.next().intValue()] = Double.NaN; } - + } - + /** * Returns a list of indexes where ranks is NaN. - * + * * @param ranks array to search for NaNs * @return list of indexes i such that ranks[i] = NaN */ @@ -406,9 +406,9 @@ public class NaturalRanking implements RankingAlgorithm { out.add(Integer.valueOf(i)); } } - return out; + return out; } - + /** * Represents the position of a double value in an ordering. * Comparable interface is implemented so Arrays.sort can be used @@ -436,7 +436,7 @@ public class NaturalRanking implements RankingAlgorithm { /** * Compare this IntDoublePair to another pair. * Only the values are compared. - * + * * @param other the other pair to compare this to * @return result of Double.compare(value, other.value) */ diff --git a/src/main/java/org/apache/commons/math/stat/ranking/RankingAlgorithm.java b/src/main/java/org/apache/commons/math/stat/ranking/RankingAlgorithm.java index 09738b54e..975f62598 100644 --- a/src/main/java/org/apache/commons/math/stat/ranking/RankingAlgorithm.java +++ b/src/main/java/org/apache/commons/math/stat/ranking/RankingAlgorithm.java @@ -19,7 +19,7 @@ package org.apache.commons.math.stat.ranking; /** * Interface representing a rank transformation. - * + * * @since 2.0 * @version $Revision$ $Date$ */ @@ -27,13 +27,13 @@ public interface RankingAlgorithm { /** *

                    Performs a rank transformation on the input data, returning an array * of ranks.

                    - * + * *

                    Ranks should be 1-based - that is, the smallest value * returned in an array of ranks should be greater than or equal to one, * rather than 0. Ranks should in general take integer values, though * implementations may return averages or other floating point values * to resolve ties in the input data.

                    - * + * * @param data array of data to be ranked * @return an array of ranks corresponding to the elements of the input array */ diff --git a/src/main/java/org/apache/commons/math/stat/ranking/TiesStrategy.java b/src/main/java/org/apache/commons/math/stat/ranking/TiesStrategy.java index acc73659b..92aab7f11 100644 --- a/src/main/java/org/apache/commons/math/stat/ranking/TiesStrategy.java +++ b/src/main/java/org/apache/commons/math/stat/ranking/TiesStrategy.java @@ -26,7 +26,7 @@ package org.apache.commons.math.stat.ranking; * of the first occurrence. For example, (1,3,4,3) is ranked as (1,2,4,2) *
                  • MAXIMUM - Tied values are assigned the maximum applicable rank, or the rank * of the last occurrence. For example, (1,3,4,3) is ranked as (1,3,4,3)
                  • - *
                  • AVERAGE - Tied values are assigned the average of the applicable ranks. + *
                  • AVERAGE - Tied values are assigned the average of the applicable ranks. * For example, (1,3,4,3) is ranked as (1,2.5,4,2.5)
                  • *
                  • AVERAGE - Tied values are assigned a random integer rank from among the * applicable values. The assigned rank will always be an integer, (inclusively) @@ -37,19 +37,19 @@ package org.apache.commons.math.stat.ranking; * @version $Revision$ $Date$ */ public enum TiesStrategy { - + /** Ties assigned sequential ranks in order of occurrence */ SEQUENTIAL, - + /** Ties get the minimum applicable rank */ MINIMUM, - + /** Ties get the maximum applicable rank */ MAXIMUM, - + /** Ties get the average of applicable ranks */ AVERAGE, - + /** Ties get a random integral value from among applicable ranks */ RANDOM } diff --git a/src/main/java/org/apache/commons/math/stat/regression/AbstractMultipleLinearRegression.java b/src/main/java/org/apache/commons/math/stat/regression/AbstractMultipleLinearRegression.java index 1fa491394..6dc95e341 100644 --- a/src/main/java/org/apache/commons/math/stat/regression/AbstractMultipleLinearRegression.java +++ b/src/main/java/org/apache/commons/math/stat/regression/AbstractMultipleLinearRegression.java @@ -39,7 +39,7 @@ public abstract class AbstractMultipleLinearRegression implements /** * Loads model x and y sample data from a flat array of data, overriding any previous sample. * Assumes that rows are concatenated with y values first in each row. - * + * * @param data input data array * @param nobs number of observations (rows) * @param nvars number of independent variables (columns, not counting y) @@ -58,10 +58,10 @@ public abstract class AbstractMultipleLinearRegression implements this.X = new Array2DRowRealMatrix(x); this.Y = new ArrayRealVector(y); } - + /** * Loads new y sample data, overriding any previous sample - * + * * @param y the [n,1] array representing the y sample */ protected void newYSampleData(double[] y) { @@ -70,7 +70,7 @@ public abstract class AbstractMultipleLinearRegression implements /** * Loads new x sample data, overriding any previous sample - * + * * @param x the [n,k] array representing the x sample */ protected void newXSampleData(double[][] x) { @@ -79,7 +79,7 @@ public abstract class AbstractMultipleLinearRegression implements /** * Validates sample data. - * + * * @param x the [n,k] array representing the x sample * @param y the [n,1] array representing the y sample * @throws IllegalArgumentException if the x and y array data are not @@ -100,7 +100,7 @@ public abstract class AbstractMultipleLinearRegression implements /** * Validates sample data. - * + * * @param x the [n,k] array representing the x sample * @param covariance the [n,n] array representing the covariance matrix * @throws IllegalArgumentException if the x sample data or covariance @@ -141,7 +141,7 @@ public abstract class AbstractMultipleLinearRegression implements public double[][] estimateRegressionParametersVariance() { return calculateBetaVariance().getData(); } - + /** * {@inheritDoc} */ @@ -165,7 +165,7 @@ public abstract class AbstractMultipleLinearRegression implements /** * Calculates the beta of multiple linear regression in matrix notation. - * + * * @return beta */ protected abstract RealVector calculateBeta(); @@ -173,14 +173,14 @@ public abstract class AbstractMultipleLinearRegression implements /** * Calculates the beta variance of multiple linear regression in matrix * notation. - * + * * @return beta variance */ protected abstract RealMatrix calculateBetaVariance(); /** * Calculates the Y variance of multiple linear regression. - * + * * @return Y variance */ protected abstract double calculateYVariance(); @@ -188,11 +188,11 @@ public abstract class AbstractMultipleLinearRegression implements /** * Calculates the residuals of multiple linear regression in matrix * notation. - * + * *
                          * u = y - X * b
                          * 
                    - * + * * @return The residuals [n,1] matrix */ protected RealVector calculateResiduals() { diff --git a/src/main/java/org/apache/commons/math/stat/regression/GLSMultipleLinearRegression.java b/src/main/java/org/apache/commons/math/stat/regression/GLSMultipleLinearRegression.java index 35d2d96d7..d9e6ca76a 100644 --- a/src/main/java/org/apache/commons/math/stat/regression/GLSMultipleLinearRegression.java +++ b/src/main/java/org/apache/commons/math/stat/regression/GLSMultipleLinearRegression.java @@ -24,13 +24,13 @@ import org.apache.commons.math.linear.RealVector; /** * The GLS implementation of the multiple linear regression. - * + * * GLS assumes a general covariance matrix Omega of the error *
                      * u ~ N(0, Omega)
                      * 
                    - * - * Estimated by GLS, + * + * Estimated by GLS, *
                      * b=(X' Omega^-1 X)^-1X'Omega^-1 y
                      * 
                    @@ -42,7 +42,7 @@ import org.apache.commons.math.linear.RealVector; * @since 2.0 */ public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegression { - + /** Covariance matrix. */ private RealMatrix Omega; @@ -64,7 +64,7 @@ public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegressio /** * Add the covariance data. - * + * * @param omega the [n,n] array representing the covariance */ protected void newCovarianceData(double[][] omega){ @@ -83,7 +83,7 @@ public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegressio } return OmegaInverse; } - + /** * Calculates beta by GLS. *
                    @@ -127,5 +127,5 @@ public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
                             double t = residuals.dotProduct(getOmegaInverse().operate(residuals));
                             return t / (X.getRowDimension() - X.getColumnDimension());
                         }
                    -    
                    +
                     }
                    diff --git a/src/main/java/org/apache/commons/math/stat/regression/MultipleLinearRegression.java b/src/main/java/org/apache/commons/math/stat/regression/MultipleLinearRegression.java
                    index 34b4c6c46..65f036de6 100644
                    --- a/src/main/java/org/apache/commons/math/stat/regression/MultipleLinearRegression.java
                    +++ b/src/main/java/org/apache/commons/math/stat/regression/MultipleLinearRegression.java
                    @@ -24,8 +24,8 @@ package org.apache.commons.math.stat.regression;
                      * where y is an n-vector regressand, X is a [n,k] matrix whose k columns are called
                      * regressors, b is k-vector of regression parameters and u is an n-vector
                      * of error terms or residuals.
                    - * 
                    - * The notation is quite standard in literature, 
                    + *
                    + * The notation is quite standard in literature,
                      * cf eg Davidson and MacKinnon, Econometrics Theory and Methods, 2004.
                      * @version $Revision$ $Date$
                      * @since 2.0
                    @@ -34,35 +34,35 @@ public interface MultipleLinearRegression {
                     
                         /**
                          * Estimates the regression parameters b.
                    -     * 
                    +     *
                          * @return The [k,1] array representing b
                          */
                         double[] estimateRegressionParameters();
                     
                         /**
                          * Estimates the variance of the regression parameters, ie Var(b).
                    -     * 
                    +     *
                          * @return The [k,k] array representing the variance of b
                          */
                         double[][] estimateRegressionParametersVariance();
                    -    
                    +
                         /**
                          * Estimates the residuals, ie u = y - X*b.
                    -     * 
                    +     *
                          * @return The [n,1] array representing the residuals
                          */
                         double[] estimateResiduals();
                     
                         /**
                          * Returns the variance of the regressand, ie Var(y).
                    -     * 
                    +     *
                          * @return The double representing the variance of y
                          */
                         double estimateRegressandVariance();
                    -    
                    +
                         /**
                          * Returns the standard errors of the regression parameters.
                    -     * 
                    +     *
                          * @return standard errors of estimated regression parameters
                          */
                          double[] estimateRegressionParametersStandardErrors();
                    diff --git a/src/main/java/org/apache/commons/math/stat/regression/OLSMultipleLinearRegression.java b/src/main/java/org/apache/commons/math/stat/regression/OLSMultipleLinearRegression.java
                    index 167ae815a..5e771e4c5 100644
                    --- a/src/main/java/org/apache/commons/math/stat/regression/OLSMultipleLinearRegression.java
                    +++ b/src/main/java/org/apache/commons/math/stat/regression/OLSMultipleLinearRegression.java
                    @@ -26,20 +26,20 @@ import org.apache.commons.math.linear.RealVector;
                     import org.apache.commons.math.linear.ArrayRealVector;
                     
                     /**
                    - * 

                    Implements ordinary least squares (OLS) to estimate the parameters of a + *

                    Implements ordinary least squares (OLS) to estimate the parameters of a * multiple linear regression model.

                    - * + * *

                    OLS assumes the covariance matrix of the error to be diagonal and with * equal variance.

                    *

                    * u ~ N(0, σ2I) *

                    - * + * *

                    The regression coefficients, b, satisfy the normal equations: *

                    * XT X b = XT y *

                    - * + * *

                    To solve the normal equations, this implementation uses QR decomposition * of the X matrix. (See {@link QRDecompositionImpl} for details on the * decomposition algorithm.) @@ -52,18 +52,18 @@ import org.apache.commons.math.linear.ArrayRealVector; * R b = QT y *

                    * Given Q and R, the last equation is solved by back-subsitution.

                    - * + * * @version $Revision$ $Date$ * @since 2.0 */ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression { - + /** Cached QR decomposition of X matrix */ private QRDecomposition qr = null; /** * Loads model x and y sample data, overriding any previous sample. - * + * * Computes and caches QR decomposition of the X matrix. * @param y the [n,1] array representing the y sample * @param x the [n,k] array representing the x sample @@ -75,10 +75,10 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio newYSampleData(y); newXSampleData(x); } - + /** * {@inheritDoc} - * + * * Computes and caches QR decomposition of the X matrix */ @Override @@ -86,7 +86,7 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio super.newSampleData(data, nobs, nvars); qr = new QRDecompositionImpl(X); } - + /** *

                    Compute the "hat" matrix. *

                    @@ -97,9 +97,9 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio * hat matrix as Q IpQT where Ip is the * p-dimensional identity matrix augmented by 0's. This computational * formula is from "The Hat Matrix in Regression and ANOVA", - * David C. Hoaglin and Roy E. Welsch, + * David C. Hoaglin and Roy E. Welsch, * The American Statistician, Vol. 32, No. 1 (Feb., 1978), pp. 17-22. - * + * * @return the hat matrix */ public RealMatrix calculateHat() { @@ -118,14 +118,14 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio } } } - + // Compute and return Hat matrix return Q.multiply(augI).multiply(Q.transpose()); } - + /** * Loads new x sample data, overriding any previous sample - * + * * @param x the [n,k] array representing the x sample */ @Override @@ -133,10 +133,10 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio this.X = new Array2DRowRealMatrix(x); qr = new QRDecompositionImpl(X); } - + /** * Calculates regression coefficients using OLS. - * + * * @return beta */ @Override @@ -151,8 +151,8 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio *

                    *

                    Uses QR decomposition to reduce (XTX)-1 * to (RTR)-1, with only the top p rows of - * R included, where p = the length of the beta vector.

                    - * + * R included, where p = the length of the beta vector.

                    + * * @return The beta variance */ @Override @@ -162,7 +162,7 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio RealMatrix Rinv = new LUDecompositionImpl(Raug).getSolver().getInverse(); return Rinv.multiply(Rinv.transpose()); } - + /** *

                    Calculates the variance on the Y by OLS. @@ -177,26 +177,26 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio return residuals.dotProduct(residuals) / (X.getRowDimension() - X.getColumnDimension()); } - - /** TODO: Find a home for the following methods in the linear package */ - + + /** TODO: Find a home for the following methods in the linear package */ + /** *

                    Uses back substitution to solve the system

                    - * + * *

                    coefficients X = constants

                    - * - *

                    coefficients must upper-triangular and constants must be a column + * + *

                    coefficients must upper-triangular and constants must be a column * matrix. The solution is returned as a column matrix.

                    - * + * *

                    The number of columns in coefficients determines the length * of the returned solution vector (column matrix). If constants * has more rows than coefficients has columns, excess rows are ignored. * Similarly, extra (zero) rows in coefficients are ignored

                    - * + * * @param coefficients upper-triangular coefficients matrix * @param constants column RHS constants vector * @return solution matrix as a column vector - * + * */ private static RealVector solveUpperTriangular(RealMatrix coefficients, RealVector constants) { @@ -210,19 +210,19 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio sum += coefficients.getEntry(index, j) * x[j]; } x[index] = (constants.getEntry(index) - sum) / coefficients.getEntry(index, index); - } + } return new ArrayRealVector(x); } - + /** *

                    Check if a matrix is upper-triangular.

                    - * + * *

                    Makes sure all below-diagonal elements are within epsilon of 0.

                    - * + * * @param m matrix to check * @param epsilon maximum allowable absolute value for elements below * the main diagonal - * + * * @throws IllegalArgumentException if m is not upper-triangular */ private static void checkUpperTriangular(RealMatrix m, double epsilon) { diff --git a/src/main/java/org/apache/commons/math/stat/regression/SimpleRegression.java b/src/main/java/org/apache/commons/math/stat/regression/SimpleRegression.java index 65a4a7cc6..78be61e70 100644 --- a/src/main/java/org/apache/commons/math/stat/regression/SimpleRegression.java +++ b/src/main/java/org/apache/commons/math/stat/regression/SimpleRegression.java @@ -29,24 +29,24 @@ import org.apache.commons.math.distribution.TDistributionImpl; *

                    * y = intercept + slope * x

                    *

                    - * Standard errors for intercept and slope are + * Standard errors for intercept and slope are * available as well as ANOVA, r-square and Pearson's r statistics.

                    *

                    - * Observations (x,y pairs) can be added to the model one at a time or they + * Observations (x,y pairs) can be added to the model one at a time or they * can be provided in a 2-dimensional array. The observations are not stored * in memory, so there is no limit to the number of observations that can be - * added to the model.

                    + * added to the model.

                    *

                    * Usage Notes:

                      *
                    • When there are fewer than two observations in the model, or when - * there is no variation in the x values (i.e. all x values are the same) + * there is no variation in the x values (i.e. all x values are the same) * all statistics return NaN. At least two observations with - * different x coordinates are requred to estimate a bivariate regression + * different x coordinates are requred to estimate a bivariate regression * model. *
                    • *
                    • getters for the statistics always compute values based on the current * set of observations -- i.e., you can get statistics, then add more data - * and get updated statistics without using a new instance. There is no + * and get updated statistics without using a new instance. There is no * "compute" method that updates all statistics. Each of the getters performs * the necessary computations to return the requested statistic.
                    • *

                    @@ -60,7 +60,7 @@ public class SimpleRegression implements Serializable { /** the distribution used to compute inference statistics. */ private TDistribution distribution; - + /** sum of x values */ private double sumX = 0d; @@ -93,7 +93,7 @@ public class SimpleRegression implements Serializable { public SimpleRegression() { this(new TDistributionImpl(1.0)); } - + /** * Create an empty SimpleRegression using the given distribution object to * compute inference statistics. @@ -104,13 +104,13 @@ public class SimpleRegression implements Serializable { super(); setDistribution(t); } - + /** * Adds the observation (x,y) to the regression data set. *

                    - * Uses updating formulas for means and sums of squares defined in + * Uses updating formulas for means and sums of squares defined in * "Algorithms for Computing the Sample Variance: Analysis and - * Recommendations", Chan, T.F., Golub, G.H., and LeVeque, R.J. + * Recommendations", Chan, T.F., Golub, G.H., and LeVeque, R.J. * 1983, American Statistician, vol. 37, pp. 242-247, referenced in * Weisberg, S. "Applied Linear Regression". 2nd Ed. 1985.

                    * @@ -134,21 +134,21 @@ public class SimpleRegression implements Serializable { sumX += x; sumY += y; n++; - + if (n > 2) { distribution.setDegreesOfFreedom(n - 2); } } - + /** * Removes the observation (x,y) from the regression data set. *

                    - * Mirrors the addData method. This method permits the use of - * SimpleRegression instances in streaming mode where the regression - * is applied to a sliding "window" of observations, however the caller is + * Mirrors the addData method. This method permits the use of + * SimpleRegression instances in streaming mode where the regression + * is applied to a sliding "window" of observations, however the caller is * responsible for maintaining the set of observations in the window.

                    - * + * * The method has no effect if there are no points of data (i.e. n=0) * * @param x independent variable value @@ -166,27 +166,27 @@ public class SimpleRegression implements Serializable { sumX -= x; sumY -= y; n--; - + if (n > 2) { distribution.setDegreesOfFreedom(n - 2); - } + } } } /** - * Adds the observations represented by the elements in + * Adds the observations represented by the elements in * data. *

                    * (data[0][0],data[0][1]) will be the first observation, then * (data[1][0],data[1][1]), etc.

                    - *

                    + *

                    * This method does not replace data that has already been added. The * observations represented by data are added to the existing * dataset.

                    - *

                    - * To replace all data, use clear() before adding the new + *

                    + * To replace all data, use clear() before adding the new * data.

                    - * + * * @param data array of observations to be added */ public void addData(double[][] data) { @@ -198,15 +198,15 @@ public class SimpleRegression implements Serializable { /** * Removes observations represented by the elements in data. - *

                    - * If the array is larger than the current n, only the first n elements are - * processed. This method permits the use of SimpleRegression instances in - * streaming mode where the regression is applied to a sliding "window" of - * observations, however the caller is responsible for maintaining the set + *

                    + * If the array is larger than the current n, only the first n elements are + * processed. This method permits the use of SimpleRegression instances in + * streaming mode where the regression is applied to a sliding "window" of + * observations, however the caller is responsible for maintaining the set * of observations in the window.

                    - *

                    + *

                    * To remove all data, use clear().

                    - * + * * @param data array of observations to be removed */ public void removeData(double[][] data) { @@ -237,7 +237,7 @@ public class SimpleRegression implements Serializable { } /** - * Returns the "predicted" y value associated with the + * Returns the "predicted" y value associated with the * supplied x value, based on the data that has been * added to the model when this method is activated. *

                    @@ -245,7 +245,7 @@ public class SimpleRegression implements Serializable { *

                    * Preconditions:

                      *
                    • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is + * must have been added before invoking this method. If this method is * invoked before a model can be estimated, Double,NaN is * returned. *

                    @@ -261,13 +261,13 @@ public class SimpleRegression implements Serializable { /** * Returns the intercept of the estimated regression line. *

                    - * The least squares estimate of the intercept is computed using the + * The least squares estimate of the intercept is computed using the * normal equations. * The intercept is sometimes denoted b0.

                    *

                    * Preconditions:

                      *
                    • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is + * must have been added before invoking this method. If this method is * invoked before a model can be estimated, Double,NaN is * returned. *

                    @@ -279,15 +279,15 @@ public class SimpleRegression implements Serializable { } /** - * Returns the slope of the estimated regression line. + * Returns the slope of the estimated regression line. *

                    - * The least squares estimate of the slope is computed using the + * The least squares estimate of the slope is computed using the * normal equations. * The slope is sometimes denoted b1.

                    *

                    * Preconditions:

                      *
                    • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is + * must have been added before invoking this method. If this method is * invoked before a model can be estimated, Double.NaN is * returned. *

                    @@ -296,7 +296,7 @@ public class SimpleRegression implements Serializable { */ public double getSlope() { if (n < 2) { - return Double.NaN; //not enough data + return Double.NaN; //not enough data } if (Math.abs(sumXX) < 10 * Double.MIN_VALUE) { return Double.NaN; //not enough variation in x @@ -306,7 +306,7 @@ public class SimpleRegression implements Serializable { /** * Returns the - * sum of squared errors (SSE) associated with the regression + * sum of squared errors (SSE) associated with the regression * model. *

                    * The sum is computed using the computational formula

                    @@ -317,16 +317,16 @@ public class SimpleRegression implements Serializable { * values about their mean, SXX is similarly defined and * SXY is the sum of the products of x and y mean deviations. *

                    - * The sums are accumulated using the updating algorithm referenced in + * The sums are accumulated using the updating algorithm referenced in * {@link #addData}.

                    *

                    - * The return value is constrained to be non-negative - i.e., if due to - * rounding errors the computational formula returns a negative result, + * The return value is constrained to be non-negative - i.e., if due to + * rounding errors the computational formula returns a negative result, * 0 is returned.

                    *

                    * Preconditions:

                      *
                    • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is + * must have been added before invoking this method. If this method is * invoked before a model can be estimated, Double,NaN is * returned. *

                    @@ -340,7 +340,7 @@ public class SimpleRegression implements Serializable { /** * Returns the sum of squared deviations of the y values about their mean. *

                    - * This is defined as SSTO + * This is defined as SSTO * here.

                    *

                    * If n < 2, this returns Double.NaN.

                    @@ -353,7 +353,7 @@ public class SimpleRegression implements Serializable { } return sumYY; } - + /** * Returns the sum of squared deviations of the x values about their mean. * @@ -367,7 +367,7 @@ public class SimpleRegression implements Serializable { } return sumXX; } - + /** * Returns the sum of crossproducts, xi*yi. * @@ -378,15 +378,15 @@ public class SimpleRegression implements Serializable { } /** - * Returns the sum of squared deviations of the predicted y values about + * Returns the sum of squared deviations of the predicted y values about * their mean (which equals the mean of y). *

                    - * This is usually abbreviated SSR or SSM. It is defined as SSM + * This is usually abbreviated SSR or SSM. It is defined as SSM * here

                    *

                    * Preconditions:

                      *
                    • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is + * must have been added before invoking this method. If this method is * invoked before a model can be estimated, Double.NaN is * returned. *

                    @@ -399,10 +399,10 @@ public class SimpleRegression implements Serializable { /** * Returns the sum of squared errors divided by the degrees of freedom, - * usually abbreviated MSE. + * usually abbreviated MSE. *

                    * If there are fewer than three data pairs in the model, - * or if there is no variation in x, this returns + * or if there is no variation in x, this returns * Double.NaN.

                    * * @return sum of squared deviations of y values @@ -417,11 +417,11 @@ public class SimpleRegression implements Serializable { /** * Returns * Pearson's product moment correlation coefficient, - * usually denoted r. + * usually denoted r. *

                    * Preconditions:

                      *
                    • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is + * must have been added before invoking this method. If this method is * invoked before a model can be estimated, Double,NaN is * returned. *

                    @@ -437,14 +437,14 @@ public class SimpleRegression implements Serializable { return result; } - /** - * Returns the + /** + * Returns the * coefficient of determination, - * usually denoted r-square. + * usually denoted r-square. *

                    * Preconditions:

                      *
                    • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is + * must have been added before invoking this method. If this method is * invoked before a model can be estimated, Double,NaN is * returned. *

                    @@ -458,11 +458,11 @@ public class SimpleRegression implements Serializable { /** * Returns the - * standard error of the intercept estimate, - * usually denoted s(b0). + * standard error of the intercept estimate, + * usually denoted s(b0). *

                    - * If there are fewer that three observations in the - * model, or if there is no variation in x, this returns + * If there are fewer that three observations in the + * model, or if there is no variation in x, this returns * Double.NaN.

                    * * @return standard error associated with intercept estimate @@ -475,12 +475,12 @@ public class SimpleRegression implements Serializable { /** * Returns the standard * error of the slope estimate, - * usually denoted s(b1). + * usually denoted s(b1). *

                    * If there are fewer that three data pairs in the model, * or if there is no variation in x, this returns Double.NaN. *

                    - * + * * @return standard error associated with slope estimate */ public double getSlopeStdErr() { @@ -493,15 +493,15 @@ public class SimpleRegression implements Serializable { *

                    * The 95% confidence interval is

                    *

                    - * (getSlope() - getSlopeConfidenceInterval(), + * (getSlope() - getSlopeConfidenceInterval(), * getSlope() + getSlopeConfidenceInterval())

                    *

                    - * If there are fewer that three observations in the - * model, or if there is no variation in x, this returns + * If there are fewer that three observations in the + * model, or if there is no variation in x, this returns * Double.NaN.

                    *

                    * Usage Note:
                    - * The validity of this statistic depends on the assumption that the + * The validity of this statistic depends on the assumption that the * observations included in the model are drawn from a * * Bivariate Normal Distribution.

                    @@ -514,33 +514,33 @@ public class SimpleRegression implements Serializable { } /** - * Returns the half-width of a (100-100*alpha)% confidence interval for + * Returns the half-width of a (100-100*alpha)% confidence interval for * the slope estimate. *

                    * The (100-100*alpha)% confidence interval is

                    *

                    - * (getSlope() - getSlopeConfidenceInterval(), + * (getSlope() - getSlopeConfidenceInterval(), * getSlope() + getSlopeConfidenceInterval())

                    *

                    - * To request, for example, a 99% confidence interval, use + * To request, for example, a 99% confidence interval, use * alpha = .01

                    *

                    * Usage Note:
                    - * The validity of this statistic depends on the assumption that the + * The validity of this statistic depends on the assumption that the * observations included in the model are drawn from a * * Bivariate Normal Distribution.

                    *

                    * Preconditions:

                      - *
                    • If there are fewer that three observations in the - * model, or if there is no variation in x, this returns + *
                    • If there are fewer that three observations in the + * model, or if there is no variation in x, this returns * Double.NaN. *
                    • - *
                    • (0 < alpha < 1); otherwise an + *
                    • (0 < alpha < 1); otherwise an * IllegalArgumentException is thrown. - *

                    + *

                  * - * @param alpha the desired significance level + * @param alpha the desired significance level * @return half-width of 95% confidence interval for the slope estimate * @throws MathException if the confidence interval can not be computed. */ @@ -556,7 +556,7 @@ public class SimpleRegression implements Serializable { } /** - * Returns the significance level of the slope (equiv) correlation. + * Returns the significance level of the slope (equiv) correlation. *

                  * Specifically, the returned value is the smallest alpha * such that the slope confidence interval with significance level @@ -564,13 +564,13 @@ public class SimpleRegression implements Serializable { * On regression output, this is often denoted Prob(|t| > 0) *

                  * Usage Note:
                  - * The validity of this statistic depends on the assumption that the + * The validity of this statistic depends on the assumption that the * observations included in the model are drawn from a * * Bivariate Normal Distribution.

                  *

                  - * If there are fewer that three observations in the - * model, or if there is no variation in x, this returns + * If there are fewer that three observations in the + * model, or if there is no variation in x, this returns * Double.NaN.

                  * * @return significance level for slope/correlation @@ -597,14 +597,14 @@ public class SimpleRegression implements Serializable { /** * Computes SSR from b1. - * + * * @param slope regression slope estimate * @return sum of squared deviations of predicted y values */ private double getRegressionSumSquares(double slope) { return slope * slope * sumXX; } - + /** * Modify the distribution used to compute inference statistics. * @param value the new distribution @@ -612,7 +612,7 @@ public class SimpleRegression implements Serializable { */ public void setDistribution(TDistribution value) { distribution = value; - + // modify degrees of freedom if (n > 2) { distribution.setDegreesOfFreedom(n - 2); diff --git a/src/main/java/org/apache/commons/math/transform/FastCosineTransformer.java b/src/main/java/org/apache/commons/math/transform/FastCosineTransformer.java index 99f1c294b..c0be10dc9 100644 --- a/src/main/java/org/apache/commons/math/transform/FastCosineTransformer.java +++ b/src/main/java/org/apache/commons/math/transform/FastCosineTransformer.java @@ -53,7 +53,7 @@ public class FastCosineTransformer implements RealTransformer { * The formula is Fn = (1/2) [f0 + (-1)n fN] + * ∑k=1N-1 fk cos(π nk/N) *

                  - * + * * @param f the real data array to be transformed * @return the real transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -68,7 +68,7 @@ public class FastCosineTransformer implements RealTransformer { * The formula is Fn = (1/2) [f0 + (-1)n fN] + * ∑k=1N-1 fk cos(π nk/N) *

                  - * + * * @param f the function to be sampled and transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -91,7 +91,7 @@ public class FastCosineTransformer implements RealTransformer { * The formula is Fn = √(1/2N) [f0 + (-1)n fN] + * √(2/N) ∑k=1N-1 fk cos(π nk/N) *

                  - * + * * @param f the real data array to be transformed * @return the real transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -109,7 +109,7 @@ public class FastCosineTransformer implements RealTransformer { * √(2/N) ∑k=1N-1 fk cos(π nk/N) * *

                  - * + * * @param f the function to be sampled and transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -134,7 +134,7 @@ public class FastCosineTransformer implements RealTransformer { * The formula is fk = (1/N) [F0 + (-1)k FN] + * (2/N) ∑n=1N-1 Fn cos(π nk/N) *

                  - * + * * @param f the real data array to be inversely transformed * @return the real inversely transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -151,7 +151,7 @@ public class FastCosineTransformer implements RealTransformer { * The formula is fk = (1/N) [F0 + (-1)k FN] + * (2/N) ∑n=1N-1 Fn cos(π nk/N) *

                  - * + * * @param f the function to be sampled and inversely transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -176,7 +176,7 @@ public class FastCosineTransformer implements RealTransformer { * The formula is fk = √(1/2N) [F0 + (-1)k FN] + * √(2/N) ∑n=1N-1 Fn cos(π nk/N) *

                  - * + * * @param f the real data array to be inversely transformed * @return the real inversely transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -191,7 +191,7 @@ public class FastCosineTransformer implements RealTransformer { * The formula is fk = √(1/2N) [F0 + (-1)k FN] + * √(2/N) ∑n=1N-1 Fn cos(π nk/N) *

                  - * + * * @param f the function to be sampled and inversely transformed * @param min the lower bound for the interval * @param max the upper bound for the interval diff --git a/src/main/java/org/apache/commons/math/transform/FastFourierTransformer.java b/src/main/java/org/apache/commons/math/transform/FastFourierTransformer.java index 3980ed749..bafb648ae 100644 --- a/src/main/java/org/apache/commons/math/transform/FastFourierTransformer.java +++ b/src/main/java/org/apache/commons/math/transform/FastFourierTransformer.java @@ -63,7 +63,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $ y_n = \Sigma_{k=0}^{N-1} e^{-2 \pi i nk/N} x_k $ *

                  - * + * * @param f the real data array to be transformed * @return the complex transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -78,7 +78,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $ y_n = \Sigma_{k=0}^{N-1} e^{-2 \pi i nk/N} x_k $ *

                  - * + * * @param f the function to be sampled and transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -100,7 +100,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $ y_n = \Sigma_{k=0}^{N-1} e^{-2 \pi i nk/N} x_k $ *

                  - * + * * @param f the complex data array to be transformed * @return the complex transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -116,7 +116,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $y_n = (1/\sqrt{N}) \Sigma_{k=0}^{N-1} e^{-2 \pi i nk/N} x_k$ *

                  - * + * * @param f the real data array to be transformed * @return the complex transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -133,7 +133,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $y_n = (1/\sqrt{N}) \Sigma_{k=0}^{N-1} e^{-2 \pi i nk/N} x_k$ *

                  - * + * * @param f the function to be sampled and transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -157,7 +157,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $y_n = (1/\sqrt{N}) \Sigma_{k=0}^{N-1} e^{-2 \pi i nk/N} x_k$ *

                  - * + * * @param f the complex data array to be transformed * @return the complex transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -175,7 +175,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $ x_k = (1/N) \Sigma_{n=0}^{N-1} e^{2 \pi i nk/N} y_n $ *

                  - * + * * @param f the real data array to be inversely transformed * @return the complex inversely transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -192,7 +192,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $ x_k = (1/N) \Sigma_{n=0}^{N-1} e^{2 \pi i nk/N} y_n $ *

                  - * + * * @param f the function to be sampled and inversely transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -216,7 +216,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $ x_k = (1/N) \Sigma_{n=0}^{N-1} e^{2 \pi i nk/N} y_n $ *

                  - * + * * @param f the complex data array to be inversely transformed * @return the complex inversely transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -234,7 +234,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $x_k = (1/\sqrt{N}) \Sigma_{n=0}^{N-1} e^{2 \pi i nk/N} y_n$ *

                  - * + * * @param f the real data array to be inversely transformed * @return the complex inversely transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -251,7 +251,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $x_k = (1/\sqrt{N}) \Sigma_{n=0}^{N-1} e^{2 \pi i nk/N} y_n$ *

                  - * + * * @param f the function to be sampled and inversely transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -275,7 +275,7 @@ public class FastFourierTransformer implements Serializable { *

                  * The formula is $x_k = (1/\sqrt{N}) \Sigma_{n=0}^{N-1} e^{2 \pi i nk/N} y_n$ *

                  - * + * * @param f the complex data array to be inversely transformed * @return the complex inversely transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -400,7 +400,7 @@ public class FastFourierTransformer implements Serializable { f[i+j+k].getImaginary() * omega_k_times_m_imaginary, f[i+j+k].getReal() * omega_k_times_m_imaginary + f[i+j+k].getImaginary() * omega_k_times_m_real); - + f[i+j+k] = f[j+k].subtract(z); f[j+k] = f[j+k].add(z); } @@ -477,7 +477,7 @@ public class FastFourierTransformer implements Serializable { /** * Returns true if the argument is power of 2. - * + * * @param n the number to test * @return true if the argument is power of 2 */ @@ -487,7 +487,7 @@ public class FastFourierTransformer implements Serializable { /** * Verifies that the data set has length of power of 2. - * + * * @param d the data array * @throws IllegalArgumentException if array length is not power of 2 */ @@ -496,12 +496,12 @@ public class FastFourierTransformer implements Serializable { throw MathRuntimeException.createIllegalArgumentException( "{0} is not a power of 2, consider padding for fix", d.length); - } + } } /** * Verifies that the data set has length of power of 2. - * + * * @param o the data array * @throws IllegalArgumentException if array length is not power of 2 */ @@ -510,12 +510,12 @@ public class FastFourierTransformer implements Serializable { throw MathRuntimeException.createIllegalArgumentException( "{0} is not a power of 2, consider padding for fix", o.length); - } + } } /** * Verifies that the endpoints specify an interval. - * + * * @param lower lower endpoint * @param upper upper endpoint * @throws IllegalArgumentException if not interval @@ -527,9 +527,9 @@ public class FastFourierTransformer implements Serializable { throw MathRuntimeException.createIllegalArgumentException( "endpoints do not specify an interval: [{0}, {1}]", lower, upper); - } + } } - + /** * Performs a multi-dimensional Fourier transform on a given array. * Use {@link #inversetransform2(Complex[])} and @@ -555,7 +555,7 @@ public class FastFourierTransformer implements Serializable { } return mdcm.getArray(); } - + /** * Performs one dimension of a multi-dimensional Fourier transform. * @@ -577,12 +577,12 @@ public class FastFourierTransformer implements Serializable { subVector[d] = i; temp[i] = mdcm.get(subVector); } - + if (forward) temp = transform2(temp); else temp = inversetransform2(temp); - + for (int i = 0; i < dimensionSize[d]; i++) { subVector[d] = i; mdcm.set(temp[i], subVector); @@ -673,15 +673,15 @@ public class FastFourierTransformer implements Serializable { "some dimensions don't match: {0} != {1}", vector.length, dimensionSize.length); } - + Object lastDimension = multiDimensionalComplexArray; - + for (int i = 0; i < dimensionSize.length; i++) { lastDimension = ((Object[]) lastDimension)[vector[i]]; } return (Complex) lastDimension; } - + /** * Set a matrix element. * @param magnitude magnitude of the element @@ -741,7 +741,7 @@ public class FastFourierTransformer implements Serializable { clone(mdcm); return mdcm; } - + /** * Copy contents of current array into mdcm. * @param mdcm array where to copy data @@ -765,15 +765,15 @@ public class FastFourierTransformer implements Serializable { } } } - + for (int[] nextVector: vectorList) { mdcm.set(get(nextVector), nextVector); } } } - - - /** Computes the nth roots of unity. + + + /** Computes the nth roots of unity. * A cache of already computed values is maintained. */ private static class RootsOfUnity implements Serializable { @@ -800,13 +800,13 @@ public class FastFourierTransformer implements Serializable { * Build an engine for computing then th roots of unity */ public RootsOfUnity() { - + omegaCount = 0; omegaReal = null; omegaImaginaryForward = null; omegaImaginaryInverse = null; isForward = true; - + } /** @@ -815,15 +815,15 @@ public class FastFourierTransformer implements Serializable { * @throws IllegalStateException if no roots of unity have been computed yet */ public synchronized boolean isForward() throws IllegalStateException { - + if (omegaCount == 0) { throw MathRuntimeException.createIllegalStateException( "roots of unity have not been computed yet"); - } + } return isForward; - + } - + /** Computes the nth roots of unity. *

                  The computed omega[] = { 1, w, w2, ... w(n-1) } where * w = exp(-2 π i / n), i = &sqrt;(-1).

                  @@ -841,10 +841,10 @@ public class FastFourierTransformer implements Serializable { } isForward = (n > 0); - + // avoid repetitive calculations final int absN = Math.abs(n); - + if (absN == omegaCount) { return; } @@ -879,7 +879,7 @@ public class FastFourierTransformer implements Serializable { */ public synchronized double getOmegaReal(int k) throws IllegalStateException, IllegalArgumentException { - + if (omegaCount == 0) { throw MathRuntimeException.createIllegalStateException( "roots of unity have not been computed yet"); @@ -889,9 +889,9 @@ public class FastFourierTransformer implements Serializable { "out of range root of unity index {0} (must be in [{1};{2}])", k, 0, omegaCount - 1); } - + return omegaReal[k]; - + } /** @@ -903,7 +903,7 @@ public class FastFourierTransformer implements Serializable { */ public synchronized double getOmegaImaginary(int k) throws IllegalStateException, IllegalArgumentException { - + if (omegaCount == 0) { throw MathRuntimeException.createIllegalStateException( "roots of unity have not been computed yet"); @@ -916,9 +916,9 @@ public class FastFourierTransformer implements Serializable { return (isForward) ? omegaImaginaryForward[k] : omegaImaginaryInverse[k]; - + } } - + } diff --git a/src/main/java/org/apache/commons/math/transform/FastHadamardTransformer.java b/src/main/java/org/apache/commons/math/transform/FastHadamardTransformer.java index 4621ef74e..9b554ad40 100644 --- a/src/main/java/org/apache/commons/math/transform/FastHadamardTransformer.java +++ b/src/main/java/org/apache/commons/math/transform/FastHadamardTransformer.java @@ -109,23 +109,23 @@ public class FastHadamardTransformer implements RealTransformer { * +----+----------+---------+----------+ *
                  * - * + * * How it works *
                    - *
                  1. Construct a matrix with N rows and n+1 columns
                    hadm[n+1][N] + *
                  2. Construct a matrix with N rows and n+1 columns
                    hadm[n+1][N] *
                    (If I use [x][y] it always means [row-offset][column-offset] of a Matrix with n rows and m columns. Its entries go from M[0][0] to M[n][m])
                  3. *
                  4. Place the input vector x[N] in the first column of the matrix hadm
                  5. *
                  6. The entries of the submatrix Dtop are calculated as follows. *
                    Dtop goes from entry [0][1] to [N/2-1][n+1]. - *
                    The columns of Dtop are the pairwise mutually exclusive sums of the previous column + *
                    The columns of Dtop are the pairwise mutually exclusive sums of the previous column *
                  7. *
                  8. The entries of the submatrix Dbottom are calculated as follows. *
                    Dbottom goes from entry [N/2][1] to [N][n+1]. - *
                    The columns of Dbottom are the pairwise differences of the previous column + *
                    The columns of Dbottom are the pairwise differences of the previous column *
                  9. *
                  10. How Dtop and Dbottom you can understand best with the example for N=8 above. *
                  11. The output vector y is now in the last column of hadm
                  12. - *
                  13. Algorithm from: http://www.archive.chipcenter.com/dsp/DSP000517F1.html
                  14. + *
                  15. Algorithm from: http://www.archive.chipcenter.com/dsp/DSP000517F1.html
                  16. *
                  *
                  * Visually @@ -146,7 +146,7 @@ public class FastHadamardTransformer implements RealTransformer { * |N | xN/2 | \/ | * +------+--------+---+---+---+-----+---+ * - * + * * @param x input vector * @return y output vector * @exception IllegalArgumentException if input array is not a power of 2 @@ -178,14 +178,14 @@ public class FastHadamardTransformer implements RealTransformer { yPrevious = yTmp; // iterate from top to bottom (row) - for (int i = 0; i < halfN; ++i) { + for (int i = 0; i < halfN; ++i) { // Dtop // The top part works with addition final int twoI = 2 * i; yCurrent[i] = yPrevious[twoI] + yPrevious[twoI + 1]; } - for (int i = halfN; i < n; ++i) { - // Dbottom + for (int i = halfN; i < n; ++i) { + // Dbottom // The bottom part works with subtraction final int twoI = 2 * i; yCurrent[i] = yPrevious[twoI - n] - yPrevious[twoI - n + 1]; @@ -229,14 +229,14 @@ public class FastHadamardTransformer implements RealTransformer { yPrevious = yTmp; // iterate from top to bottom (row) - for (int i = 0; i < halfN; ++i) { + for (int i = 0; i < halfN; ++i) { // Dtop // The top part works with addition final int twoI = 2 * i; yCurrent[i] = yPrevious[twoI] + yPrevious[twoI + 1]; } - for (int i = halfN; i < n; ++i) { - // Dbottom + for (int i = halfN; i < n; ++i) { + // Dbottom // The bottom part works with subtraction final int twoI = 2 * i; yCurrent[i] = yPrevious[twoI - n] - yPrevious[twoI - n + 1]; diff --git a/src/main/java/org/apache/commons/math/transform/FastSineTransformer.java b/src/main/java/org/apache/commons/math/transform/FastSineTransformer.java index eb69c77f8..727910f43 100644 --- a/src/main/java/org/apache/commons/math/transform/FastSineTransformer.java +++ b/src/main/java/org/apache/commons/math/transform/FastSineTransformer.java @@ -34,7 +34,7 @@ import org.apache.commons.math.complex.Complex; * In addition, the first element must be 0 and it's enforced in function * transformation after sampling.

                  *

                  As of version 2.0 this no longer implements Serializable

                  - * + * * @version $Revision$ $Date$ * @since 1.2 */ @@ -52,7 +52,7 @@ public class FastSineTransformer implements RealTransformer { *

                  * The formula is Fn = ∑k=0N-1 fk sin(π nk/N) *

                  - * + * * @param f the real data array to be transformed * @return the real transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -67,7 +67,7 @@ public class FastSineTransformer implements RealTransformer { *

                  * The formula is Fn = ∑k=0N-1 fk sin(π nk/N) *

                  - * + * * @param f the function to be sampled and transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -91,7 +91,7 @@ public class FastSineTransformer implements RealTransformer { *

                  * The formula is Fn = √(2/N) ∑k=0N-1 fk sin(π nk/N) *

                  - * + * * @param f the real data array to be transformed * @return the real transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -107,7 +107,7 @@ public class FastSineTransformer implements RealTransformer { *

                  * The formula is Fn = √(2/N) ∑k=0N-1 fk sin(π nk/N) *

                  - * + * * @param f the function to be sampled and transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -132,7 +132,7 @@ public class FastSineTransformer implements RealTransformer { *

                  * The formula is fk = (2/N) ∑n=0N-1 Fn sin(π nk/N) *

                  - * + * * @param f the real data array to be inversely transformed * @return the real inversely transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -148,7 +148,7 @@ public class FastSineTransformer implements RealTransformer { *

                  * The formula is fk = (2/N) ∑n=0N-1 Fn sin(π nk/N) *

                  - * + * * @param f the function to be sampled and inversely transformed * @param min the lower bound for the interval * @param max the upper bound for the interval @@ -172,7 +172,7 @@ public class FastSineTransformer implements RealTransformer { *

                  * The formula is fk = √(2/N) ∑n=0N-1 Fn sin(π nk/N) *

                  - * + * * @param f the real data array to be inversely transformed * @return the real inversely transformed array * @throws IllegalArgumentException if any parameters are invalid @@ -187,7 +187,7 @@ public class FastSineTransformer implements RealTransformer { *

                  * The formula is fk = √(2/N) ∑n=0N-1 Fn sin(π nk/N) *

                  - * + * * @param f the function to be sampled and inversely transformed * @param min the lower bound for the interval * @param max the upper bound for the interval diff --git a/src/main/java/org/apache/commons/math/transform/RealTransformer.java b/src/main/java/org/apache/commons/math/transform/RealTransformer.java index 779e90efe..f875e91b3 100644 --- a/src/main/java/org/apache/commons/math/transform/RealTransformer.java +++ b/src/main/java/org/apache/commons/math/transform/RealTransformer.java @@ -79,4 +79,4 @@ public interface RealTransformer { double[] inversetransform(UnivariateRealFunction f, double min, double max, int n) throws FunctionEvaluationException, IllegalArgumentException; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/math/util/BigRealField.java b/src/main/java/org/apache/commons/math/util/BigRealField.java index 430ab9466..775ec0457 100644 --- a/src/main/java/org/apache/commons/math/util/BigRealField.java +++ b/src/main/java/org/apache/commons/math/util/BigRealField.java @@ -70,7 +70,7 @@ public class BigRealField implements Field, Serializable { */ private Object readResolve() { // return the singleton instance - return LazyHolder.INSTANCE; + return LazyHolder.INSTANCE; } } diff --git a/src/main/java/org/apache/commons/math/util/CompositeFormat.java b/src/main/java/org/apache/commons/math/util/CompositeFormat.java index 998a5574f..4a42e81d3 100644 --- a/src/main/java/org/apache/commons/math/util/CompositeFormat.java +++ b/src/main/java/org/apache/commons/math/util/CompositeFormat.java @@ -36,7 +36,7 @@ public abstract class CompositeFormat extends Format { /** * Create a default number format. The default number format is based on * {@link NumberFormat#getInstance()} with the only customizing that the - * maximum number of fraction digits is set to 2. + * maximum number of fraction digits is set to 2. * @return the default number format. */ protected static NumberFormat getDefaultNumberFormat() { @@ -46,7 +46,7 @@ public abstract class CompositeFormat extends Format { /** * Create a default number format. The default number format is based on * {@link NumberFormat#getInstance(java.util.Locale)} with the only - * customizing that the maximum number of fraction digits is set to 2. + * customizing that the maximum number of fraction digits is set to 2. * @param locale the specific locale used by the format. * @return the default number format specific to the given locale. */ @@ -81,19 +81,19 @@ public abstract class CompositeFormat extends Format { int index = pos.getIndex(); final int n = source.length(); char ret = 0; - + if (index < n) { char c; do { c = source.charAt(index++); } while (Character.isWhitespace(c) && index < n); pos.setIndex(index); - + if (index < n) { ret = c; } } - + return ret; } @@ -109,12 +109,12 @@ public abstract class CompositeFormat extends Format { private Number parseNumber(final String source, final double value, final ParsePosition pos) { Number ret = null; - + StringBuffer sb = new StringBuffer(); sb.append('('); sb.append(value); sb.append(')'); - + final int n = sb.length(); final int startIndex = pos.getIndex(); final int endIndex = startIndex + n; @@ -124,7 +124,7 @@ public abstract class CompositeFormat extends Format { pos.setIndex(endIndex); } } - + return ret; } @@ -143,7 +143,7 @@ public abstract class CompositeFormat extends Format { final int startIndex = pos.getIndex(); Number number = format.parse(source, pos); final int endIndex = pos.getIndex(); - + // check for error parsing number if (startIndex == endIndex) { // try parsing special numbers @@ -157,7 +157,7 @@ public abstract class CompositeFormat extends Format { } } } - + return number; } @@ -218,4 +218,4 @@ public abstract class CompositeFormat extends Format { return toAppendTo; } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/math/util/ContinuedFraction.java b/src/main/java/org/apache/commons/math/util/ContinuedFraction.java index d82c239c2..c633b2f96 100644 --- a/src/main/java/org/apache/commons/math/util/ContinuedFraction.java +++ b/src/main/java/org/apache/commons/math/util/ContinuedFraction.java @@ -35,7 +35,7 @@ import org.apache.commons.math.MaxIterationsExceededException; * @version $Revision$ $Date$ */ public abstract class ContinuedFraction { - + /** Maximum allowed numerical error. */ private static final double DEFAULT_EPSILON = 10e-9; @@ -67,7 +67,7 @@ public abstract class ContinuedFraction { /** * Evaluates the continued fraction at the value x. * @param x the evaluation point. - * @return the value of the continued fraction evaluated at x. + * @return the value of the continued fraction evaluated at x. * @throws MathException if the algorithm fails to converge. */ public double evaluate(double x) throws MathException { @@ -78,7 +78,7 @@ public abstract class ContinuedFraction { * Evaluates the continued fraction at the value x. * @param x the evaluation point. * @param epsilon maximum error allowed. - * @return the value of the continued fraction evaluated at x. + * @return the value of the continued fraction evaluated at x. * @throws MathException if the algorithm fails to converge. */ public double evaluate(double x, double epsilon) throws MathException { @@ -89,7 +89,7 @@ public abstract class ContinuedFraction { * Evaluates the continued fraction at the value x. * @param x the evaluation point. * @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 MathException if the algorithm fails to converge. */ public double evaluate(double x, int maxIterations) throws MathException { @@ -100,7 +100,7 @@ public abstract class ContinuedFraction { *

                  * Evaluates the continued fraction at the value x. *

                  - * + * *

                  * The implementation of this method is based on equations 14-17 of: *

                  - * + * * @param n the size of the set * @param k the size of the subsets to be counted * @return n choose k @@ -186,7 +186,7 @@ public final class MathUtils { // Use symmetry for large k if (k > n / 2) return binomialCoefficient(n, n - k); - + // We use the formula // (n choose k) = n! / (n-k)! / k! // (n choose k) == ((n-k+1)*...*n) / (1*...*k) @@ -239,7 +239,7 @@ public final class MathUtils { * Double.MAX_VALUE is 1029. If the computed value exceeds Double.MAX_VALUE, * Double.POSITIVE_INFINITY is returned
                • *

                - * + * * @param n the size of the set * @param k the size of the subsets to be counted * @return n choose k @@ -259,15 +259,15 @@ public final class MathUtils { if (n < 67) { return binomialCoefficient(n,k); } - + double result = 1d; for (int i = 1; i <= k; i++) { result *= (double)(n - k + i) / (double)i; } - + return Math.floor(result + 0.5); } - + /** * Returns the natural log of the Binomial @@ -280,7 +280,7 @@ public final class MathUtils { *
              • 0 <= k <= n (otherwise * IllegalArgumentException is thrown)
              • *

              - * + * * @param n the size of the set * @param k the size of the subsets to be counted * @return n choose k @@ -294,22 +294,22 @@ public final class MathUtils { if ((k == 1) || (k == n - 1)) { return Math.log(n); } - + /* * For values small enough to do exact integer computation, - * return the log of the exact value + * return the log of the exact value */ - if (n < 67) { + if (n < 67) { return Math.log(binomialCoefficient(n,k)); } - + /* * Return the log of binomialCoefficientDouble for values that will not * overflow binomialCoefficientDouble */ - if (n < 1030) { + if (n < 1030) { return Math.log(binomialCoefficientDouble(n, k)); - } + } if (k > n / 2) { return binomialCoefficientLog(n, n - k); @@ -330,7 +330,7 @@ public final class MathUtils { logSum -= Math.log(i); } - return logSum; + return logSum; } /** @@ -352,10 +352,10 @@ public final class MathUtils { n); } } - + /** * Compares two numbers given some amount of allowed error. - * + * * @param x the first number * @param y the second number * @param eps the amount of error to allow when checking for equality @@ -371,22 +371,22 @@ public final class MathUtils { } return 1; } - + /** * Returns the * hyperbolic cosine of x. - * + * * @param x double value for which to find the hyperbolic cosine * @return hyperbolic cosine of x */ public static double cosh(double x) { return (Math.exp(x) + Math.exp(-x)) / 2.0; } - + /** * Returns true iff both arguments are NaN or neither is NaN and they are * equal - * + * * @param x first value * @param y second value * @return true if the values are equal or both are NaN @@ -401,7 +401,7 @@ public final class MathUtils { *

              * Two NaNs are considered equals, as are two infinities with same sign. *

              - * + * * @param x first value * @param y second value * @param eps the amount of absolute error to allow @@ -410,7 +410,7 @@ public final class MathUtils { public static boolean equals(double x, double y, double eps) { return equals(x, y) || (Math.abs(y - x) <= eps); } - + /** * Returns true iff both arguments are equal or within the range of allowed * error (inclusive). @@ -447,7 +447,7 @@ public final class MathUtils { /** * Returns true iff both arguments are null or have same dimensions * and all their elements are {@link #equals(double,double) equals} - * + * * @param x first array * @param y second array * @return true if the values are both null or have same dimension @@ -468,9 +468,9 @@ public final class MathUtils { } return true; } - + /** All long-representable factorials */ - private static final long[] FACTORIALS = new long[] + private static final long[] FACTORIALS = new long[] {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800l, 87178291200l, 1307674368000l, 20922789888000l, 355687428096000l, 6402373705728000l, 121645100408832000l, @@ -491,7 +491,7 @@ public final class MathUtils { * an ArithMeticException is thrown. *
            *

            - * + * * @param n argument * @return n! * @throws ArithmeticException if the result is too large to be represented @@ -526,7 +526,7 @@ public final class MathUtils { * Double.MAX_VALUE, Double.POSITIVE_INFINITY is returned *
          *

          - * + * * @param n argument * @return n! * @throws IllegalArgumentException if n < 0 @@ -551,7 +551,7 @@ public final class MathUtils { *
        • n >= 0 (otherwise * IllegalArgumentException is thrown)
        • *

        - * + * * @param n argument * @return n! * @throws IllegalArgumentException if preconditions are not met. @@ -593,7 +593,7 @@ public final class MathUtils { *
      • The invocation gcd(0, 0) is the only one which returns * 0.
      • *
      - * + * * @param p any number * @param q any number * @return the greatest common divisor, never negative @@ -664,7 +664,7 @@ public final class MathUtils { /** * Returns an integer hash code representing the given double value. - * + * * @param value the value to be hashed * @return the hash code */ @@ -674,7 +674,7 @@ public final class MathUtils { /** * Returns an integer hash code representing the given double array. - * + * * @param value the value to be hashed (may be null) * @return the hash code * @since 1.2 @@ -686,7 +686,7 @@ public final class MathUtils { /** * For a byte value x, this method returns (byte)(+1) if x >= 0 and * (byte)(-1) if x < 0. - * + * * @param x the value, a byte * @return (byte)(+1) or (byte)(-1), depending on the sign of x */ @@ -698,7 +698,7 @@ public final class MathUtils { * For a double precision value x, this method returns +1.0 if x >= 0 and * -1.0 if x < 0. Returns NaN if x is * NaN. - * + * * @param x the value, a double * @return +1.0 or -1.0, depending on the sign of x */ @@ -712,7 +712,7 @@ public final class MathUtils { /** * For a float value x, this method returns +1.0F if x >= 0 and -1.0F if x < * 0. Returns NaN if x is NaN. - * + * * @param x the value, a float * @return +1.0F or -1.0F, depending on the sign of x */ @@ -725,7 +725,7 @@ public final class MathUtils { /** * For an int value x, this method returns +1 if x >= 0 and -1 if x < 0. - * + * * @param x the value, an int * @return +1 or -1, depending on the sign of x */ @@ -735,7 +735,7 @@ public final class MathUtils { /** * For a long value x, this method returns +1L if x >= 0 and -1L if x < 0. - * + * * @param x the value, a long * @return +1L or -1L, depending on the sign of x */ @@ -746,7 +746,7 @@ public final class MathUtils { /** * For a short value x, this method returns (short)(+1) if x >= 0 and * (short)(-1) if x < 0. - * + * * @param x the value, a short * @return (short)(+1) or (short)(-1), depending on the sign of x */ @@ -768,7 +768,7 @@ public final class MathUtils { *
    • The result of lcm(0, x) and lcm(x, 0) is * 0 for any x. *
    - * + * * @param a any number * @param b any number * @return the least common multiple, never negative @@ -788,29 +788,29 @@ public final class MathUtils { return lcm; } - /** - *

    Returns the + /** + *

    Returns the * logarithm * for base b of x. *

    - *

    Returns NaN if either argument is negative. If + *

    Returns NaN if either argument is negative. If * base is 0 and x is positive, 0 is returned. - * If base is positive and x is 0, + * If base is positive and x is 0, * Double.NEGATIVE_INFINITY is returned. If both arguments * are 0, the result is NaN.

    - * + * * @param base the base of the logarithm, must be greater than 0 * @param x argument, must be greater than 0 * @return the value of the logarithm - the number y such that base^y = x. * @since 1.2 - */ + */ public static double log(double base, double x) { return Math.log(x)/Math.log(base); } /** * Multiply two integers, checking for overflow. - * + * * @param x a factor * @param y a factor * @return the product x*y @@ -828,7 +828,7 @@ public final class MathUtils { /** * Multiply two long integers, checking for overflow. - * + * * @param a first value * @param b second value * @return the product a * b @@ -857,7 +857,7 @@ public final class MathUtils { ret = a * b; } else { throw new ArithmeticException(msg); - + } } else { // assert b == 0 @@ -866,7 +866,7 @@ public final class MathUtils { } else if (a > 0) { // assert a > 0 // assert b > 0 - + // check for positive overflow with positive a, positive b if (a <= Long.MAX_VALUE / b) { ret = a * b; @@ -891,7 +891,7 @@ public final class MathUtils { * strictly less than d is returned.

    *

    * If d is NaN or Infinite, it is returned unchanged.

    - * + * * @param d base number * @param direction (the only important thing is whether * direction is greater or smaller than d) @@ -941,7 +941,7 @@ public final class MathUtils { /** * Scale a number by 2scaleFactor. *

    If d is 0 or NaN or Infinite, it is returned unchanged.

    - * + * * @param d base number * @param scaleFactor power of two by which d sould be multiplied * @return d × 2scaleFactor @@ -987,21 +987,21 @@ public final class MathUtils { public static double normalizeAngle(double a, double center) { return a - TWO_PI * Math.floor((a + Math.PI - center) / TWO_PI); } - + /** - *

    Normalizes an array to make it sum to a specified value. + *

    Normalizes an array to make it sum to a specified value. * Returns the result of the transformation

           *    x |-> x * normalizedSum / sum
           * 
    * 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.

    - * + * *

    Throws IllegalArgumentException if normalizedSum is infinite * or NaN and ArithmeticException if the input array contains any infinite elements * or sums to 0

    - * + * *

    Ignores (i.e., copies unchanged to the output array) NaNs in the input array.

    - * + * * @param values input array to be normalized * @param normalizedSum target sum for the normalized array * @return normalized array @@ -1032,7 +1032,7 @@ public final class MathUtils { } if (sum == 0) { throw MathRuntimeException.createArithmeticException( - "Array sums to zero"); + "Array sums to zero"); } for (int i = 0; i < len; i++) { if (Double.isNaN(values[i])) { @@ -1041,13 +1041,13 @@ public final class MathUtils { out[i] = values[i] * normalizedSum / sum; } } - return out; + return out; } /** * Round the given value to the specified number of decimal places. The * value is rounded using the {@link BigDecimal#ROUND_HALF_UP} method. - * + * * @param x the value to round. * @param scale the number of digits to the right of the decimal point. * @return the rounded value. @@ -1061,7 +1061,7 @@ public final class MathUtils { * Round the given value to the specified number of decimal places. The * value is rounded using the given method which is any method defined in * {@link BigDecimal}. - * + * * @param x the value to round. * @param scale the number of digits to the right of the decimal point. * @param roundingMethod the rounding method as defined in @@ -1077,7 +1077,7 @@ public final class MathUtils { .doubleValue(); } catch (NumberFormatException ex) { if (Double.isInfinite(x)) { - return x; + return x; } else { return Double.NaN; } @@ -1087,7 +1087,7 @@ public final class MathUtils { /** * Round the given value to the specified number of decimal places. The * value is rounding using the {@link BigDecimal#ROUND_HALF_UP} method. - * + * * @param x the value to round. * @param scale the number of digits to the right of the decimal point. * @return the rounded value. @@ -1101,7 +1101,7 @@ public final class MathUtils { * Round the given value to the specified number of decimal places. The * value is rounded using the given method which is any method defined in * {@link BigDecimal}. - * + * * @param x the value to round. * @param scale the number of digits to the right of the decimal point. * @param roundingMethod the rounding method as defined in @@ -1119,7 +1119,7 @@ public final class MathUtils { * Round the given non-negative, value to the "nearest" integer. Nearest is * determined by the rounding method specified. Rounding methods are defined * in {@link BigDecimal}. - * + * * @param unscaled the value to round. * @param sign the sign of the original, scaled value. * @param roundingMethod the rounding method as defined in @@ -1215,7 +1215,7 @@ public final class MathUtils { *

    * For a byte value x, this method returns (byte)(+1) if x > 0, (byte)(0) if * x = 0, and (byte)(-1) if x < 0.

    - * + * * @param x the value, a byte * @return (byte)(+1), (byte)(0), or (byte)(-1), depending on the sign of x */ @@ -1231,7 +1231,7 @@ public final class MathUtils { * +1.0 if x > 0, 0.0 if * x = 0.0, and -1.0 if x < 0. * Returns NaN if x is NaN.

    - * + * * @param x the value, a double * @return +1.0, 0.0, or -1.0, depending on the sign of x */ @@ -1249,7 +1249,7 @@ public final class MathUtils { * For a float value x, this method returns +1.0F if x > 0, 0.0F if x = * 0.0F, and -1.0F if x < 0. Returns NaN if x * is NaN.

    - * + * * @param x the value, a float * @return +1.0F, 0.0F, or -1.0F, depending on the sign of x */ @@ -1266,7 +1266,7 @@ public final class MathUtils { *

    * For an int value x, this method returns +1 if x > 0, 0 if x = 0, and -1 * if x < 0.

    - * + * * @param x the value, an int * @return +1, 0, or -1, depending on the sign of x */ @@ -1280,7 +1280,7 @@ public final class MathUtils { *

    * For a long value x, this method returns +1L if x > 0, 0L if x = 0, and * -1L if x < 0.

    - * + * * @param x the value, a long * @return +1L, 0L, or -1L, depending on the sign of x */ @@ -1294,7 +1294,7 @@ public final class MathUtils { *

    * For a short value x, this method returns (short)(+1) if x > 0, (short)(0) * if x = 0, and (short)(-1) if x < 0.

    - * + * * @param x the value, a short * @return (short)(+1), (short)(0), or (short)(-1), depending on the sign of * x @@ -1306,7 +1306,7 @@ public final class MathUtils { /** * Returns the * hyperbolic sine of x. - * + * * @param x double value for which to find the hyperbolic sine * @return hyperbolic sine of x */ @@ -1316,7 +1316,7 @@ public final class MathUtils { /** * Subtract two integers, checking for overflow. - * + * * @param x the minuend * @param y the subtrahend * @return the difference x-y @@ -1334,7 +1334,7 @@ public final class MathUtils { /** * Subtract two long integers, checking for overflow. - * + * * @param a first value * @param b second value * @return the difference a-b @@ -1572,7 +1572,7 @@ public final class MathUtils { } return sum; } - + /** * Calculates the L1 (sum of abs) distance between two points. * @@ -1603,7 +1603,7 @@ public final class MathUtils { } return Math.sqrt(sum); } - + /** * Calculates the L2 (Euclidean) distance between two points. * @@ -1619,7 +1619,7 @@ public final class MathUtils { } return Math.sqrt(sum); } - + /** * Calculates the L (max of abs) distance between two points. * @@ -1634,7 +1634,7 @@ public final class MathUtils { } return max; } - + /** * Calculates the L (max of abs) distance between two points. * @@ -1650,5 +1650,5 @@ public final class MathUtils { return max; } - + } diff --git a/src/main/java/org/apache/commons/math/util/NumberTransformer.java b/src/main/java/org/apache/commons/math/util/NumberTransformer.java index 9f34ece7e..e866b7b2e 100644 --- a/src/main/java/org/apache/commons/math/util/NumberTransformer.java +++ b/src/main/java/org/apache/commons/math/util/NumberTransformer.java @@ -21,19 +21,19 @@ import org.apache.commons.math.MathException; /** * Subclasses implementing this interface can transform Objects to doubles. * @version $Revision$ $Date$ - * + * * No longer extends Serializable since 2.0 - * + * */ public interface NumberTransformer { - + /** * Implementing this interface provides a facility to transform * from Object to Double. - * + * * @param o the Object to be transformed. * @return the double value of the Object. - * @throws MathException if the Object can not be transformed into a Double. + * @throws MathException if the Object can not be transformed into a Double. */ double transform(Object o) throws MathException; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/math/util/OpenIntToDoubleHashMap.java b/src/main/java/org/apache/commons/math/util/OpenIntToDoubleHashMap.java index 0d803f9a0..f288d30d1 100644 --- a/src/main/java/org/apache/commons/math/util/OpenIntToDoubleHashMap.java +++ b/src/main/java/org/apache/commons/math/util/OpenIntToDoubleHashMap.java @@ -281,7 +281,7 @@ public class OpenIntToDoubleHashMap implements Serializable { j = probe(perturb, j); index = j & mask; perturb >>= PERTURB_SHIFT; - + if (states[index] != FULL || keys[index] == key) { break; } @@ -340,7 +340,7 @@ public class OpenIntToDoubleHashMap implements Serializable { return size; } - + /** * Remove the value associated with a key. * @param key key to which the value is associated @@ -475,7 +475,7 @@ public class OpenIntToDoubleHashMap implements Serializable { return h ^ (h >>> 7) ^ (h >>> 4); } - + /** Iterator class for the map. */ public class Iterator { @@ -592,5 +592,5 @@ public class OpenIntToDoubleHashMap implements Serializable { count = 0; } - + } diff --git a/src/main/java/org/apache/commons/math/util/OpenIntToFieldHashMap.java b/src/main/java/org/apache/commons/math/util/OpenIntToFieldHashMap.java index 8ddd7ec8e..3de831b41 100644 --- a/src/main/java/org/apache/commons/math/util/OpenIntToFieldHashMap.java +++ b/src/main/java/org/apache/commons/math/util/OpenIntToFieldHashMap.java @@ -40,7 +40,7 @@ import org.apache.commons.math.MathRuntimeException; * @since 2.0 */ public class OpenIntToFieldHashMap> implements Serializable { - + /** Serializable version identifier. */ private static final long serialVersionUID = -9179080286849120720L; @@ -71,7 +71,7 @@ public class OpenIntToFieldHashMap> implements Seriali /** Field to which the elements belong. */ private final Field field; - + /** Keys table. */ private int[] keys; @@ -293,7 +293,7 @@ public class OpenIntToFieldHashMap> implements Seriali j = probe(perturb, j); index = j & mask; perturb >>= PERTURB_SHIFT; - + if (states[index] != FULL || keys[index] == key) { break; } @@ -352,7 +352,7 @@ public class OpenIntToFieldHashMap> implements Seriali return size; } - + /** * Remove the value associated with a key. * @param key key to which the value is associated @@ -487,7 +487,7 @@ public class OpenIntToFieldHashMap> implements Seriali return h ^ (h >>> 7) ^ (h >>> 4); } - + /** Iterator class for the map. */ public class Iterator { diff --git a/src/main/java/org/apache/commons/math/util/ResizableDoubleArray.java b/src/main/java/org/apache/commons/math/util/ResizableDoubleArray.java index 6b9695ae1..b29615702 100644 --- a/src/main/java/org/apache/commons/math/util/ResizableDoubleArray.java +++ b/src/main/java/org/apache/commons/math/util/ResizableDoubleArray.java @@ -23,36 +23,36 @@ import org.apache.commons.math.MathRuntimeException; /** *

    - * A variable length {@link DoubleArray} implementation that automatically - * handles expanding and contracting its internal storage array as elements + * A variable length {@link DoubleArray} implementation that automatically + * handles expanding and contracting its internal storage array as elements * are added and removed. *

    *

    * The internal storage array starts with capacity determined by the * initialCapacity property, which can be set by the constructor. - * The default initial capacity is 16. Adding elements using - * {@link #addElement(double)} appends elements to the end of the array. When - * there are no open entries at the end of the internal storage array, the - * array is expanded. The size of the expanded array depends on the - * expansionMode and expansionFactor properties. - * The expansionMode determines whether the size of the array is - * multiplied by the expansionFactor (MULTIPLICATIVE_MODE) or if + * The default initial capacity is 16. Adding elements using + * {@link #addElement(double)} appends elements to the end of the array. When + * there are no open entries at the end of the internal storage array, the + * array is expanded. The size of the expanded array depends on the + * expansionMode and expansionFactor properties. + * The expansionMode determines whether the size of the array is + * multiplied by the expansionFactor (MULTIPLICATIVE_MODE) or if * the expansion is additive (ADDITIVE_MODE -- expansionFactor - * storage locations added). The default expansionMode is + * storage locations added). The default expansionMode is * MULTIPLICATIVE_MODE and the default expansionFactor * is 2.0. *

    *

    * The {@link #addElementRolling(double)} method adds a new element to the end - * of the internal storage array and adjusts the "usable window" of the - * internal array forward by one position (effectively making what was the + * of the internal storage array and adjusts the "usable window" of the + * internal array forward by one position (effectively making what was the * second element the first, and so on). Repeated activations of this method * (or activation of {@link #discardFrontElements(int)}) will effectively orphan * the storage locations at the beginning of the internal storage array. To * reclaim this storage, each time one of these methods is activated, the size - * of the internal storage array is compared to the number of addressable + * of the internal storage array is compared to the number of addressable * elements (the numElements property) and if the difference - * is too large, the internal array is contracted to size + * is too large, the internal array is contracted to size * numElements + 1. The determination of when the internal * storage array is "too large" depends on the expansionMode and * contractionFactor properties. If the expansionMode @@ -60,11 +60,11 @@ import org.apache.commons.math.MathRuntimeException; * ratio between storage array length and numElements exceeds * contractionFactor. If the expansionMode * is ADDITIVE_MODE, the number of excess storage locations - * is compared to contractionFactor. + * is compared to contractionFactor. *

    *

    - * To avoid cycles of expansions and contractions, the - * expansionFactor must not exceed the + * To avoid cycles of expansions and contractions, the + * expansionFactor must not exceed the * contractionFactor. Constructors and mutators for both of these * properties enforce this requirement, throwing IllegalArgumentException if it * is violated. @@ -72,33 +72,33 @@ import org.apache.commons.math.MathRuntimeException; * @version $Revision$ $Date$ */ public class ResizableDoubleArray implements DoubleArray, Serializable { - + /** Serializable version identifier */ - private static final long serialVersionUID = -3485529955529426875L; - + private static final long serialVersionUID = -3485529955529426875L; + /** additive expansion mode */ public static final int ADDITIVE_MODE = 1; - + /** multiplicative expansion mode */ public static final int MULTIPLICATIVE_MODE = 0; - - /** - * The contraction criteria determines when the internal array will be + + /** + * The contraction criteria determines when the internal array will be * contracted to fit the number of elements contained in the element * array + 1. */ protected float contractionCriteria = 2.5f; - /** - * The expansion factor of the array. When the array needs to be expanded, - * the new array size will be + /** + * The expansion factor of the array. When the array needs to be expanded, + * the new array size will be * internalArray.length * expansionFactor * if expansionMode is set to MULTIPLICATIVE_MODE, or - * internalArray.length + expansionFactor if + * internalArray.length + expansionFactor if * expansionMode is set to ADDITIVE_MODE. */ protected float expansionFactor = 2.0f; - + /** * Determines whether array expansion by expansionFactor * is additive or multiplicative. @@ -110,19 +110,19 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { * property as it is only meaningful when passed to a constructor. */ protected int initialCapacity = 16; - - /** + + /** * The internal storage array. */ protected double[] internalArray; - /** + /** * The number of addressable elements in the array. Note that this * has nothing to do with the length of the internal storage array. */ protected int numElements = 0; - /** + /** * The position of the first addressable element in the internal storage * array. The addressable elements in the array are * internalArray[startIndex],...,internalArray[startIndex + numElements -1] @@ -161,7 +161,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { /** *

    - * Create a ResizableArray with the specified initial capacity + * Create a ResizableArray with the specified initial capacity * and expansion factor. The remaining properties take default * values: *

      @@ -175,9 +175,9 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { *
    • initialCapacity > 0
    • *
    • expansionFactor > 1
    • *

    - * + * * @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 * @throws IllegalArgumentException if parameters are not valid */ @@ -190,7 +190,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { /** *

    - * Create a ResizableArray with the specified initialCapacity, + * Create a ResizableArray with the specified initialCapacity, * expansionFactor, and contractionCriteria. The expansionMode * will default to MULTIPLICATIVE_MODE.

    *

    @@ -202,7 +202,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { *

  • contractionFactor >= expansionFactor
  • *

* @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 * @param contractionCriteria The contraction Criteria. * @throws IllegalArgumentException if parameters are not valid @@ -214,7 +214,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { setInitialCapacity(initialCapacity); internalArray = new double[initialCapacity]; } - + /** *

* Create a ResizableArray with the specified properties.

@@ -228,9 +228,9 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { *
  • expansionMode in {MULTIPLICATIVE_MODE, ADDITIVE_MODE} *
  • *

    - * + * * @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 * @param contractionCriteria the contraction Criteria * @param expansionMode the expansion mode @@ -244,13 +244,13 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { setExpansionMode(expansionMode); internalArray = new double[initialCapacity]; } - + /** * Copy constructor. Creates a new ResizableDoubleArray that is a deep, * fresh copy of the original. Needs to acquire synchronization lock * on original. Original may not be null; otherwise a NullPointerException * is thrown. - * + * * @param original array to copy * @since 2.0 */ @@ -260,7 +260,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { /** * Adds an element to the end of this expandable array. - * + * * @param value to be added to end of array */ public synchronized void addElement(double value) { @@ -285,7 +285,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { * and addElementRolling(5) is invoked, the result is an array containing * the entries 2, 3, 4, 5 and the value returned is 1. *

    - * + * * @param value the value to be added to the array * @return the value which has been discarded or "pushed" out of the array * by this rolling insert @@ -308,12 +308,12 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { } return discarded; } - + /** * Substitutes value for the most recently added value. - * Returns the value that has been replaced. If the array is empty (i.e. + * Returns the value that has been replaced. If the array is empty (i.e. * if {@link #numElements} is zero), a MathRuntimeException is thrown. - * + * * @param value new value to substitute for the most recently added value * @return value that has been replaced in the array * @since 2.0 @@ -331,12 +331,12 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { return discarded; } - + /** - * Checks the expansion factor and the contraction criteria and throws an - * IllegalArgumentException if the contractionCriteria is less than the + * Checks the expansion factor and the contraction criteria and throws an + * IllegalArgumentException if the contractionCriteria is less than the * expansionCriteria - * + * * @param expansion factor to be checked * @param contraction criteria to be checked * @throws IllegalArgumentException if the contractionCriteria is less than @@ -366,9 +366,9 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { expansion); } } - + /** - * Clear the array, reset the size to the initialCapacity and the number + * Clear the array, reset the size to the initialCapacity and the number * of elements to zero. */ public synchronized void clear() { @@ -376,11 +376,11 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { startIndex = 0; internalArray = new double[initialCapacity]; } - + /** - * Contracts the storage array to the (size of the element set) + 1 - to - * avoid a zero length array. This function also resets the startIndex to - * zero. + * Contracts the storage array to the (size of the element set) + 1 - to + * avoid a zero length array. This function also resets the startIndex to + * zero. */ public synchronized void contract() { double[] tempArray = new double[numElements + 1]; @@ -395,11 +395,11 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { /** * Discards the i initial elements of the array. For example, - * if the array contains the elements 1,2,3,4, invoking - * discardFrontElements(2) will cause the first two elements + * if the array contains the elements 1,2,3,4, invoking + * discardFrontElements(2) will cause the first two elements * to be discarded, leaving 3,4 in the array. Throws illegalArgumentException * if i exceeds numElements. - * + * * @param i the number of elements to discard from the front of the array * @throws IllegalArgumentException if i is greater than numElements. * @since 2.0 @@ -407,16 +407,16 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { public synchronized void discardFrontElements(int i) { discardExtremeElements(i,true); - + } /** * Discards the i last elements of the array. For example, - * if the array contains the elements 1,2,3,4, invoking - * discardMostRecentElements(2) will cause the last two elements + * if the array contains the elements 1,2,3,4, invoking + * discardMostRecentElements(2) will cause the last two elements * to be discarded, leaving 1,2 in the array. Throws illegalArgumentException * if i exceeds numElements. - * + * * @param i the number of elements to discard from the end of the array * @throws IllegalArgumentException if i is greater than numElements. * @since 2.0 @@ -424,25 +424,25 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { public synchronized void discardMostRecentElements(int i) { discardExtremeElements(i,false); - + } - + /** * Discards the i first or last elements of the array, * depending on the value of front. - * For example, if the array contains the elements 1,2,3,4, invoking - * discardExtremeElements(2,false) will cause the last two elements + * For example, if the array contains the elements 1,2,3,4, invoking + * discardExtremeElements(2,false) will cause the last two elements * to be discarded, leaving 1,2 in the array. - * For example, if the array contains the elements 1,2,3,4, invoking - * discardExtremeElements(2,true) will cause the first two elements + * For example, if the array contains the elements 1,2,3,4, invoking + * discardExtremeElements(2,true) will cause the first two elements * to be discarded, leaving 3,4 in the array. * Throws illegalArgumentException * if i exceeds numElements. - * + * * @param i the number of elements to discard from the front/end of the array * @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 + * of the array * @throws IllegalArgumentException if i is greater than numElements. * @since 2.0 */ @@ -456,7 +456,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { "cannot discard a negative number of elements ({0})", i); } else { - // "Subtract" this number of discarded from numElements + // "Subtract" this number of discarded from numElements numElements -= i; if (front) startIndex += i; } @@ -476,10 +476,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { */ protected synchronized void expand() { - // notice the use of Math.ceil(), this guarantees that we will always - // have an array of at least currentSize + 1. Assume that the + // notice the use of Math.ceil(), this guarantees that we will always + // have an array of at least currentSize + 1. Assume that the // current initial capacity is 1 and the expansion factor - // is 1.000000000000000001. The newly calculated size will be + // is 1.000000000000000001. The newly calculated size will be // rounded up to 2 after the multiplication is performed. int newSize = 0; if (expansionMode == MULTIPLICATIVE_MODE) { @@ -493,10 +493,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { System.arraycopy(internalArray, 0, tempArray, 0, internalArray.length); internalArray = tempArray; } - + /** * Expands the internal storage array to the specified size. - * + * * @param size Size of the new internal storage array */ private synchronized void expandTo(int size) { @@ -507,24 +507,24 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { } /** - * The contraction criteria defines when the internal array will contract - * to store only the number of elements in the element array. + * The contraction criteria defines when the internal array will contract + * to store only the number of elements in the element array. * If the expansionMode is MULTIPLICATIVE_MODE, - * contraction is triggered when the ratio between storage array length + * contraction is triggered when the ratio between storage array length * and numElements exceeds contractionFactor. * If the expansionMode is ADDITIVE_MODE, the - * number of excess storage locations is compared to - * contractionFactor. - * + * number of excess storage locations is compared to + * contractionFactor. + * * @return the contraction criteria used to reclaim memory. */ public float getContractionCriteria() { return contractionCriteria; } - + /** * Returns the element at the specified index - * + * * @param index index to fetch a value from * @return value stored at the specified index * @throws ArrayIndexOutOfBoundsException if index is less than @@ -543,9 +543,9 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { index); } } - + /** - * Returns a double array containing the elements of this + * Returns a double array containing the elements of this * ResizableArray. This method returns a copy, not a * reference to the underlying array, so that changes made to the returned * array have no effect on this ResizableArray. @@ -557,40 +557,40 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { numElements); return elementArray; } - + /** - * The expansion factor controls the size of a new array when an array + * The expansion factor controls the size of a new array when an array * needs to be expanded. The expansionMode - * determines whether the size of the array is multiplied by the - * expansionFactor (MULTIPLICATIVE_MODE) or if + * determines whether the size of the array is multiplied by the + * expansionFactor (MULTIPLICATIVE_MODE) or if * the expansion is additive (ADDITIVE_MODE -- expansionFactor - * storage locations added). The default expansionMode is + * storage locations added). The default expansionMode is * MULTIPLICATIVE_MODE and the default expansionFactor * is 2.0. - * + * * @return the expansion factor of this expandable double array */ public float getExpansionFactor() { return expansionFactor; } - + /** - * The expansionMode determines whether the internal storage - * array grows additively (ADDITIVE_MODE) or multiplicatively + * The expansionMode determines whether the internal storage + * array grows additively (ADDITIVE_MODE) or multiplicatively * (MULTIPLICATIVE_MODE) when it is expanded. - * + * * @return Returns the expansionMode. */ public int getExpansionMode() { return expansionMode; } - + /** - * Notice the package scope on this method. This method is simply here - * for the JUnit test, it allows us check if the expansion is working - * properly after a number of expansions. This is not meant to be a part + * Notice the package scope on this method. This method is simply here + * for the JUnit test, it allows us check if the expansion is working + * properly after a number of expansions. This is not meant to be a part * of the public interface of this class. - * + * * @return the length of the internal storage array. */ synchronized int getInternalLength() { @@ -599,14 +599,14 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { /** * Returns the number of elements currently in the array. Please note - * that this is different from the length of the internal storage array. + * that this is different from the length of the internal storage array. * * @return number of elements */ public synchronized int getNumElements() { return (numElements); } - + /** * Returns the internal storage array. Note that this method returns * a reference to the internal storage array, not a copy, and to correctly @@ -615,7 +615,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { * only be used in cases where copying the internal array is not practical. * The {@link #getElements} method should be used in all other cases. * - * + * * @return the internal storage array used by this object * @deprecated replaced by {@link #getInternalValues()} as of 2.0 */ @@ -632,7 +632,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { * only be used in cases where copying the internal array is not practical. * The {@link #getElements} method should be used in all other cases. * - * + * * @return the internal storage array used by this object * @since 2.0 */ @@ -641,8 +641,8 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { } /** - * Sets the contraction criteria for this ExpandContractDoubleArray. - * + * Sets the contraction criteria for this ExpandContractDoubleArray. + * * @param contractionCriteria contraction criteria */ public void setContractionCriteria(float contractionCriteria) { @@ -651,15 +651,15 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { this.contractionCriteria = contractionCriteria; } } - + /** * Sets the element at the specified index. If the specified index is greater than * getNumElements() - 1, the numElements property - * is increased to index +1 and additional storage is allocated - * (if necessary) for the new element and all (uninitialized) elements + * is increased to index +1 and additional storage is allocated + * (if necessary) for the new element and all (uninitialized) elements * between the new element and the previous end of the array). - * + * * @param index index to store a value in * @param value value to store at the specified index * @throws ArrayIndexOutOfBoundsException if index is less than @@ -673,15 +673,15 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { } if (index + 1 > numElements) { numElements = index + 1; - } + } if ((startIndex + index) >= internalArray.length) { expandTo(startIndex + (index + 1)); - } + } internalArray[startIndex + index] = value; } /** - * Sets the expansionFactor. Throws IllegalArgumentException if the + * Sets the expansionFactor. Throws IllegalArgumentException if the * the following conditions are not met: *
      *
    • expansionFactor > 1
    • @@ -702,12 +702,12 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { /** * Sets the expansionMode. The specified value must be one of * ADDITIVE_MODE, MULTIPLICATIVE_MODE. - * + * * @param expansionMode The expansionMode to set. * @throws IllegalArgumentException if the specified mode value is not valid */ public void setExpansionMode(int expansionMode) { - if (expansionMode != MULTIPLICATIVE_MODE && + if (expansionMode != MULTIPLICATIVE_MODE && expansionMode != ADDITIVE_MODE) { throw MathRuntimeException.createIllegalArgumentException( "unsupported expansion mode {0}, supported modes are {1} ({2}) and {3} ({4})", @@ -718,10 +718,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { this.expansionMode = expansionMode; } } - + /** * Sets the initial capacity. Should only be invoked by constructors. - * + * * @param initialCapacity of the array * @throws IllegalArgumentException if initialCapacity is not * positive. @@ -737,12 +737,12 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { initialCapacity); } } - + /** - * This function allows you to control the number of elements contained - * in this array, and can be used to "throw out" the last n values in an + * This function allows you to control the number of elements contained + * in this array, and can be used to "throw out" the last n values in an * array. This function will also expand the internal array as needed. - * + * * @param i a new number of elements * @throws IllegalArgumentException if i is negative. */ @@ -755,7 +755,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { i); } - // Test the new num elements, check to see if the array needs to be + // Test the new num elements, check to see if the array needs to be // expanded to accommodate this new number of elements if ((startIndex + i) > internalArray.length) { expandTo(startIndex + i); @@ -766,13 +766,13 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { } /** - * Returns true if the internal storage array has too many unused - * storage positions. - * + * Returns true if the internal storage array has too many unused + * storage positions. + * * @return true if array satisfies the contraction criteria */ private synchronized boolean shouldContract() { - if (expansionMode == MULTIPLICATIVE_MODE) { + if (expansionMode == MULTIPLICATIVE_MODE) { return (internalArray.length / ((float) numElements)) > contractionCriteria; } else { return (internalArray.length - numElements) > contractionCriteria; @@ -791,22 +791,22 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { public synchronized int start() { return startIndex; } - + /** *

      Copies source to dest, copying the underlying data, so dest is * a new, independent copy of source. Does not contract before * the copy.

      - * + * *

      Obtains synchronization locks on both source and dest * (in that order) before performing the copy.

      - * + * *

      Neither source nor dest may be null; otherwise a NullPointerException * is thrown

      - * + * * @param source ResizableDoubleArray to copy * @param dest ResizableArray to replace with a copy of the source array * @since 2.0 - * + * */ public static void copy(ResizableDoubleArray source, ResizableDoubleArray dest) { synchronized(source) { @@ -823,11 +823,11 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { } } } - + /** * Returns a copy of the ResizableDoubleArray. Does not contract before * the copy, so the returned object is an exact copy of this. - * + * * @return a new ResizableDoubleArray with the same data and configuration * properties as this * @since 2.0 @@ -837,11 +837,11 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { copy(this, result); return result; } - + /** * Returns true iff object is a ResizableDoubleArray with the same properties * as this and an identical internal storage array. - * + * * @param object object to be compared for equality with this * @return true iff object is a ResizableDoubleArray with the same data and * properties as this @@ -865,7 +865,7 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { result = result && (other.expansionMode == expansionMode); result = result && (other.numElements == numElements); result = result && (other.startIndex == startIndex); - if (!result) { + if (!result) { return false; } else { return Arrays.equals(internalArray, other.internalArray); @@ -873,10 +873,10 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { } } } - + /** * Returns a hash code consistent with equals. - * + * * @return hash code representing this ResizableDoubleArray * @since 2.0 */ @@ -892,5 +892,5 @@ public class ResizableDoubleArray implements DoubleArray, Serializable { hashData[6] = startIndex; return Arrays.hashCode(hashData); } - + } diff --git a/src/main/java/org/apache/commons/math/util/TransformerMap.java b/src/main/java/org/apache/commons/math/util/TransformerMap.java index 326b96c41..a898e68c2 100644 --- a/src/main/java/org/apache/commons/math/util/TransformerMap.java +++ b/src/main/java/org/apache/commons/math/util/TransformerMap.java @@ -26,7 +26,7 @@ import org.apache.commons.math.MathException; /** * This TansformerMap automates the transformation of mixed object types. - * It provides a means to set NumberTransformers that will be selected + * It provides a means to set NumberTransformers that will be selected * based on the Class of the object handed to the Maps * double transform(Object o) method. * @version $Revision$ $Date$ @@ -120,7 +120,7 @@ public class TransformerMap implements NumberTransformer, Serializable { } /** - * Returns the Set of NumberTransformers used as values + * Returns the Set of NumberTransformers used as values * in the map. * @return Set of NumberTransformers */ @@ -131,10 +131,10 @@ public class TransformerMap implements NumberTransformer, Serializable { /** * Attempts to transform the Object against the map of * NumberTransformers. Otherwise it returns Double.NaN. - * + * * @param o the Object to be transformed. * @return the double value of the Object. - * @throws MathException if the Object can not be transformed into a Double. + * @throws MathException if the Object can not be transformed into a Double. * @see org.apache.commons.math.util.NumberTransformer#transform(java.lang.Object) */ public double transform(Object o) throws MathException { @@ -155,7 +155,7 @@ public class TransformerMap implements NumberTransformer, Serializable { /** {@inheritDoc} */ @Override public boolean equals(Object other) { - if (this == other) { + if (this == other) { return true; } if (other == null) { @@ -179,7 +179,7 @@ public class TransformerMap implements NumberTransformer, Serializable { return false; } } - + /** {@inheritDoc} */ @Override public int hashCode() { diff --git a/src/test/java/org/apache/commons/math/ArgumentOutsideDomainExceptionTest.java b/src/test/java/org/apache/commons/math/ArgumentOutsideDomainExceptionTest.java index eac05706d..b8c4e22d9 100644 --- a/src/test/java/org/apache/commons/math/ArgumentOutsideDomainExceptionTest.java +++ b/src/test/java/org/apache/commons/math/ArgumentOutsideDomainExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class ArgumentOutsideDomainExceptionTest extends TestCase { - + public void testConstructor(){ ArgumentOutsideDomainException ex = new ArgumentOutsideDomainException(Math.PI, 10.0, 20.0); assertNull(ex.getCause()); @@ -34,5 +34,5 @@ public class ArgumentOutsideDomainExceptionTest extends TestCase { assertEquals(Math.PI, ex.getArgument()[0], 0); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + } diff --git a/src/test/java/org/apache/commons/math/ConvergenceExceptionTest.java b/src/test/java/org/apache/commons/math/ConvergenceExceptionTest.java index 430c44d85..fdc74356e 100644 --- a/src/test/java/org/apache/commons/math/ConvergenceExceptionTest.java +++ b/src/test/java/org/apache/commons/math/ConvergenceExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,7 +33,7 @@ public class ConvergenceExceptionTest extends TestCase { assertNotNull(ex.getMessage(Locale.FRENCH)); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + public void testConstructorPatternArguments(){ String pattern = "a {0}x{1} matrix cannot be a rotation matrix"; Object[] arguments = { Integer.valueOf(6), Integer.valueOf(4) }; @@ -47,7 +47,7 @@ public class ConvergenceExceptionTest extends TestCase { assertFalse(pattern.equals(ex.getMessage())); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + public void testConstructorCause(){ String inMsg = "inner message"; Exception cause = new Exception(inMsg); @@ -70,5 +70,5 @@ public class ConvergenceExceptionTest extends TestCase { assertFalse(pattern.equals(ex.getMessage())); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + } diff --git a/src/test/java/org/apache/commons/math/DuplicateSampleAbscissaExceptionTest.java b/src/test/java/org/apache/commons/math/DuplicateSampleAbscissaExceptionTest.java index 66e4b6e6e..26a48b566 100644 --- a/src/test/java/org/apache/commons/math/DuplicateSampleAbscissaExceptionTest.java +++ b/src/test/java/org/apache/commons/math/DuplicateSampleAbscissaExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class DuplicateSampleAbscissaExceptionTest extends TestCase { - + public void testConstructor(){ DuplicateSampleAbscissaException ex = new DuplicateSampleAbscissaException(1.2, 10, 11); assertNull(ex.getCause()); @@ -34,5 +34,5 @@ public class DuplicateSampleAbscissaExceptionTest extends TestCase { assertEquals(1.2, ex.getDuplicateAbscissa(), 0); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + } diff --git a/src/test/java/org/apache/commons/math/FunctionEvaluationExceptionTest.java b/src/test/java/org/apache/commons/math/FunctionEvaluationExceptionTest.java index 119aa4e5d..87f845bd1 100644 --- a/src/test/java/org/apache/commons/math/FunctionEvaluationExceptionTest.java +++ b/src/test/java/org/apache/commons/math/FunctionEvaluationExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class FunctionEvaluationExceptionTest extends TestCase { - + public void testConstructor(){ FunctionEvaluationException ex = new FunctionEvaluationException(0.0); assertNull(ex.getCause()); @@ -33,7 +33,7 @@ public class FunctionEvaluationExceptionTest extends TestCase { assertTrue(ex.getMessage().indexOf("0") > 0); assertEquals(0.0, ex.getArgument()[0], 0); } - + public void testConstructorArray(){ FunctionEvaluationException ex = new FunctionEvaluationException(new double[] { 0, 1, 2 }); @@ -44,7 +44,7 @@ public class FunctionEvaluationExceptionTest extends TestCase { assertEquals(1.0, ex.getArgument()[1], 0); assertEquals(2.0, ex.getArgument()[2], 0); } - + public void testConstructorPatternArguments(){ String pattern = "evaluation failed for argument = {0}"; Object[] arguments = { Double.valueOf(0.0) }; diff --git a/src/test/java/org/apache/commons/math/MathConfigurationExceptionTest.java b/src/test/java/org/apache/commons/math/MathConfigurationExceptionTest.java index e62c4d2e2..2d9b1e68f 100644 --- a/src/test/java/org/apache/commons/math/MathConfigurationExceptionTest.java +++ b/src/test/java/org/apache/commons/math/MathConfigurationExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ public class MathConfigurationExceptionTest extends TestCase { assertNull(ex.getMessage()); assertEquals(0, ex.getMessage(Locale.FRENCH).length()); } - + public void testConstructorPatternArguments(){ String pattern = "a {0}x{1} matrix cannot be a rotation matrix"; Object[] arguments = { Integer.valueOf(6), Integer.valueOf(4) }; @@ -46,7 +46,7 @@ public class MathConfigurationExceptionTest extends TestCase { assertFalse(pattern.equals(ex.getMessage())); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + public void testConstructorCause(){ String inMsg = "inner message"; Exception cause = new Exception(inMsg); @@ -69,5 +69,5 @@ public class MathConfigurationExceptionTest extends TestCase { assertFalse(pattern.equals(ex.getMessage())); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + } diff --git a/src/test/java/org/apache/commons/math/MathExceptionTest.java b/src/test/java/org/apache/commons/math/MathExceptionTest.java index ba6ec94a5..9131d7d2f 100644 --- a/src/test/java/org/apache/commons/math/MathExceptionTest.java +++ b/src/test/java/org/apache/commons/math/MathExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,7 +35,7 @@ public class MathExceptionTest extends TestCase { assertNull(ex.getMessage()); assertEquals(0, ex.getMessage(Locale.FRENCH).length()); } - + public void testConstructorPatternArguments(){ String pattern = "a {0}x{1} matrix cannot be a rotation matrix"; Object[] arguments = { Integer.valueOf(6), Integer.valueOf(4) }; @@ -49,7 +49,7 @@ public class MathExceptionTest extends TestCase { assertFalse(pattern.equals(ex.getMessage())); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + public void testConstructorCause(){ String inMsg = "inner message"; Exception cause = new Exception(inMsg); @@ -72,7 +72,7 @@ public class MathExceptionTest extends TestCase { assertFalse(pattern.equals(ex.getMessage())); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + /** * Tests the printStackTrace() operation. */ @@ -86,18 +86,18 @@ public class MathExceptionTest extends TestCase { ex.printStackTrace(ps); String stack = baos.toString(); String outerMsg = "org.apache.commons.math.MathException: outer message"; - String innerMsg = "Caused by: " + + String innerMsg = "Caused by: " + "org.apache.commons.math.MathConfigurationException: inner message"; assertTrue(stack.startsWith(outerMsg)); assertTrue(stack.indexOf(innerMsg) > 0); - + PrintWriter pw = new PrintWriter(ps, true); ex.printStackTrace(pw); stack = baos.toString(); assertTrue(stack.startsWith(outerMsg)); assertTrue(stack.indexOf(innerMsg) > 0); } - + /** * Test serialization */ @@ -107,17 +107,17 @@ public class MathExceptionTest extends TestCase { MathException cause = new MathConfigurationException(inMsg); MathException ex = new MathException(cause, outMsg); MathException image = (MathException) TestUtils.serializeAndRecover(ex); - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ex.printStackTrace(ps); String stack = baos.toString(); - + ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); PrintStream ps2 = new PrintStream(baos2); image.printStackTrace(ps2); String stack2 = baos2.toString(); - + // See if JDK supports nested exceptions. If not, stack trace of // inner exception will not be serialized boolean jdkSupportsNesting = false; @@ -127,7 +127,7 @@ public class MathExceptionTest extends TestCase { } catch (NoSuchMethodException e) { jdkSupportsNesting = false; } - + if (jdkSupportsNesting) { assertEquals(stack, stack2); } else { diff --git a/src/test/java/org/apache/commons/math/MaxIterationsExceededExceptionTest.java b/src/test/java/org/apache/commons/math/MaxIterationsExceededExceptionTest.java index 5e20ca80a..6c04ae9a6 100644 --- a/src/test/java/org/apache/commons/math/MaxIterationsExceededExceptionTest.java +++ b/src/test/java/org/apache/commons/math/MaxIterationsExceededExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class MaxIterationsExceededExceptionTest extends TestCase { - + public void testSimpleConstructor(){ MaxIterationsExceededException ex = new MaxIterationsExceededException(1000000); assertNull(ex.getCause()); @@ -47,5 +47,5 @@ public class MaxIterationsExceededExceptionTest extends TestCase { assertEquals(1000000, ex.getMaxIterations()); assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH))); } - + } diff --git a/src/test/java/org/apache/commons/math/RetryTestCase.java b/src/test/java/org/apache/commons/math/RetryTestCase.java index e4ae9a08b..3d14e9b12 100644 --- a/src/test/java/org/apache/commons/math/RetryTestCase.java +++ b/src/test/java/org/apache/commons/math/RetryTestCase.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,8 +23,8 @@ import junit.framework.TestCase; /** * A TestCase that retries tests when assertions fail. *

      - * If one or more tests throw an AssertionFailedError, all tests are - * repeated one time. + * If one or more tests throw an AssertionFailedError, all tests are + * repeated one time. *

      * Errors or exceptions other than AssertionFailedError do not lead to retries. * @@ -39,7 +39,7 @@ public abstract class RetryTestCase extends TestCase { public RetryTestCase(String arg0) { super(arg0); } - + /** * Override runTest() to catch AssertionFailedError and retry */ @@ -50,7 +50,7 @@ public abstract class RetryTestCase extends TestCase { } catch (AssertionFailedError err) { // System.out.println("Retrying " + this.getName()); super.runTest(); - } + } } } diff --git a/src/test/java/org/apache/commons/math/TestUtils.java b/src/test/java/org/apache/commons/math/TestUtils.java index 679483f6c..59f30b723 100644 --- a/src/test/java/org/apache/commons/math/TestUtils.java +++ b/src/test/java/org/apache/commons/math/TestUtils.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -63,7 +63,7 @@ public class TestUtils { Assert.assertEquals(msg, expected, actual, delta); } } - + /** * Verifies that the two arguments are exactly the same, either * both NaN or infinities of same sign, or identical floating point values. @@ -71,7 +71,7 @@ public class TestUtils { public static void assertSame(double expected, double actual) { assertEquals(expected, actual, 0); } - + /** * Verifies that real and imaginary parts of the two complex arguments * are exactly the same. Also ensures that NaN / infinite components match. @@ -80,7 +80,7 @@ public class TestUtils { assertSame(expected.getReal(), actual.getReal()); assertSame(expected.getImaginary(), actual.getImaginary()); } - + /** * Verifies that real and imaginary parts of the two complex arguments * differ by at most delta. Also ensures that NaN / infinite components match. @@ -89,18 +89,18 @@ public class TestUtils { assertEquals(expected.getReal(), actual.getReal(), delta); assertEquals(expected.getImaginary(), actual.getImaginary(), delta); } - + /** * Verifies that two double arrays have equal entries, up to tolerance */ public static void assertEquals(double expected[], double observed[], double tolerance) { assertEquals("Array comparison failure", expected, observed, tolerance); } - + /** * Serializes an object to a bytes array and then recovers the object from the bytes array. * Returns the deserialized object. - * + * * @param o object to serialize and recover * @return the recovered, deserialized object */ @@ -121,11 +121,11 @@ public class TestUtils { return null; } } - + /** * Verifies that serialization preserves equals and hashCode. * Serializes the object, then recovers it and checks equals and hash code. - * + * * @param object the object to serialize and recover */ public static void checkSerializedEquality(Object object) { @@ -138,7 +138,7 @@ public class TestUtils { * Verifies that the relative error in actual vs. expected is less than or * equal to relativeError. If expected is infinite or NaN, actual must be * the same (NaN or infinity of the same sign). - * + * * @param expected expected value * @param actual observed value * @param relativeError maximum allowable relative error @@ -147,12 +147,12 @@ public class TestUtils { double relativeError) { assertRelativelyEquals(null, expected, actual, relativeError); } - + /** * Verifies that the relative error in actual vs. expected is less than or * equal to relativeError. If expected is infinite or NaN, actual must be * the same (NaN or infinity of the same sign). - * + * * @param msg message to return with failure * @param expected expected value * @param actual observed value @@ -173,10 +173,10 @@ public class TestUtils { Assert.assertEquals(msg, 0.0, x, relativeError); } } - + /** * Fails iff values does not contain a number within epsilon of z. - * + * * @param msg message to return with failure * @param values complex array to search * @param z value sought @@ -189,33 +189,33 @@ public class TestUtils { while (!found && i < values.length) { try { assertEquals(values[i], z, epsilon); - found = true; + found = true; } catch (AssertionFailedError er) { // no match } i++; } if (!found) { - Assert.fail(msg + + Assert.fail(msg + " Unable to find " + ComplexFormat.formatComplex(z)); } } - + /** * Fails iff values does not contain a number within epsilon of z. - * + * * @param values complex array to search * @param z value sought * @param epsilon tolerance */ public static void assertContains(Complex[] values, Complex z, double epsilon) { - assertContains(null, values, z, epsilon); + assertContains(null, values, z, epsilon); } - + /** * Fails iff values does not contain a number within epsilon of x. - * + * * @param msg message to return with failure * @param values double array to search * @param x value sought @@ -228,7 +228,7 @@ public class TestUtils { while (!found && i < values.length) { try { assertEquals(values[i], x, epsilon); - found = true; + found = true; } catch (AssertionFailedError er) { // no match } @@ -238,10 +238,10 @@ public class TestUtils { Assert.fail(msg + " Unable to find" + x); } } - + /** * Fails iff values does not contain a number within epsilon of x. - * + * * @param values double array to search * @param x value sought * @param epsilon tolerance @@ -250,19 +250,19 @@ public class TestUtils { double epsilon) { assertContains(null, values, x, epsilon); } - - /** verifies that two matrices are close (1-norm) */ + + /** verifies that two matrices are close (1-norm) */ public static void assertEquals(String msg, RealMatrix expected, RealMatrix observed, double tolerance) { - + if (observed == null) { Assert.fail(msg + "\nObserved is null"); } - - if (expected.getColumnDimension() != observed.getColumnDimension() || + + if (expected.getColumnDimension() != observed.getColumnDimension() || expected.getRowDimension() != observed.getRowDimension()) { StringBuffer messageBuffer = new StringBuffer(msg); - messageBuffer.append("\nObserved has incorrect dimensions."); + messageBuffer.append("\nObserved has incorrect dimensions."); messageBuffer.append("\nobserved is " + observed.getRowDimension() + " x " + observed.getColumnDimension()); messageBuffer.append("\nexpected " + expected.getRowDimension() + @@ -279,19 +279,19 @@ public class TestUtils { Assert.fail(messageBuffer.toString()); } } - - /** verifies that two matrices are equal */ + + /** verifies that two matrices are equal */ public static void assertEquals(FieldMatrix> expected, FieldMatrix> observed) { - + if (observed == null) { Assert.fail("Observed is null"); } - - if (expected.getColumnDimension() != observed.getColumnDimension() || + + if (expected.getColumnDimension() != observed.getColumnDimension() || expected.getRowDimension() != observed.getRowDimension()) { StringBuffer messageBuffer = new StringBuffer(); - messageBuffer.append("Observed has incorrect dimensions."); + messageBuffer.append("Observed has incorrect dimensions."); messageBuffer.append("\nobserved is " + observed.getRowDimension() + " x " + observed.getColumnDimension()); messageBuffer.append("\nexpected " + expected.getRowDimension() + @@ -307,7 +307,7 @@ public class TestUtils { } } } - + /** verifies that two arrays are close (sup norm) */ public static void assertEquals(String msg, double[] expected, double[] observed, double tolerance) { @@ -332,14 +332,14 @@ public class TestUtils { out.append(" expected = "); out.append(expected[i]); out.append(" observed = "); - out.append(observed[i]); + out.append(observed[i]); } } if (failure) { Assert.fail(out.toString()); } } - + /** verifies that two arrays are equal */ public static > void assertEquals(T[] m, T[] n) { if (m.length != n.length) { @@ -349,5 +349,5 @@ public class TestUtils { Assert.assertEquals(m[i],n[i]); } } - + } diff --git a/src/test/java/org/apache/commons/math/analysis/MonitoredFunction.java b/src/test/java/org/apache/commons/math/analysis/MonitoredFunction.java index 2fe7d1e37..22edc84cf 100644 --- a/src/test/java/org/apache/commons/math/analysis/MonitoredFunction.java +++ b/src/test/java/org/apache/commons/math/analysis/MonitoredFunction.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +21,7 @@ import org.apache.commons.math.FunctionEvaluationException; /** * Wrapper class for counting functions calls. * - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public class MonitoredFunction implements UnivariateRealFunction { diff --git a/src/test/java/org/apache/commons/math/analysis/QuinticFunction.java b/src/test/java/org/apache/commons/math/analysis/QuinticFunction.java index e87f80d2e..f29330228 100644 --- a/src/test/java/org/apache/commons/math/analysis/QuinticFunction.java +++ b/src/test/java/org/apache/commons/math/analysis/QuinticFunction.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +21,7 @@ import org.apache.commons.math.FunctionEvaluationException; /** * Auxillary class for testing solvers. * - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public class QuinticFunction implements DifferentiableUnivariateRealFunction { diff --git a/src/test/java/org/apache/commons/math/analysis/SinFunction.java b/src/test/java/org/apache/commons/math/analysis/SinFunction.java index be1f5f8c9..d75bb3afb 100644 --- a/src/test/java/org/apache/commons/math/analysis/SinFunction.java +++ b/src/test/java/org/apache/commons/math/analysis/SinFunction.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ import org.apache.commons.math.FunctionEvaluationException; * has an inflection point there (second order derivative is zero), * which means linear approximation (Regula Falsi) will converge * quadratically. - * + * * @version $Revision$ $Date$ */ public class SinFunction implements DifferentiableUnivariateRealFunction { diff --git a/src/test/java/org/apache/commons/math/analysis/integration/RombergIntegratorTest.java b/src/test/java/org/apache/commons/math/analysis/integration/RombergIntegratorTest.java index 38971ac02..cc82960c4 100644 --- a/src/test/java/org/apache/commons/math/analysis/integration/RombergIntegratorTest.java +++ b/src/test/java/org/apache/commons/math/analysis/integration/RombergIntegratorTest.java @@ -29,8 +29,8 @@ import junit.framework.TestCase; * Romberg algorithm is very fast for good behavior integrand. Test runs * show that for a default relative accuracy of 1E-6, it generally takes * takes less than 5 iterations for the integral to converge. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class RombergIntegratorTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/integration/SimpsonIntegratorTest.java b/src/test/java/org/apache/commons/math/analysis/integration/SimpsonIntegratorTest.java index bbbab8472..ef1d0d5ff 100644 --- a/src/test/java/org/apache/commons/math/analysis/integration/SimpsonIntegratorTest.java +++ b/src/test/java/org/apache/commons/math/analysis/integration/SimpsonIntegratorTest.java @@ -28,8 +28,8 @@ import junit.framework.TestCase; *

      * Test runs show that for a default relative accuracy of 1E-6, it * generally takes 5 to 10 iterations for the integral to converge. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class SimpsonIntegratorTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/integration/TrapezoidIntegratorTest.java b/src/test/java/org/apache/commons/math/analysis/integration/TrapezoidIntegratorTest.java index 4bf9de045..5479f2fb1 100644 --- a/src/test/java/org/apache/commons/math/analysis/integration/TrapezoidIntegratorTest.java +++ b/src/test/java/org/apache/commons/math/analysis/integration/TrapezoidIntegratorTest.java @@ -28,8 +28,8 @@ import junit.framework.TestCase; *

      * Test runs show that for a default relative accuracy of 1E-6, it * generally takes 10 to 15 iterations for the integral to converge. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class TrapezoidIntegratorTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/interpolation/DividedDifferenceInterpolatorTest.java b/src/test/java/org/apache/commons/math/analysis/interpolation/DividedDifferenceInterpolatorTest.java index 3ef2311b3..f8f402a9a 100644 --- a/src/test/java/org/apache/commons/math/analysis/interpolation/DividedDifferenceInterpolatorTest.java +++ b/src/test/java/org/apache/commons/math/analysis/interpolation/DividedDifferenceInterpolatorTest.java @@ -34,8 +34,8 @@ import junit.framework.TestCase; * Since zeta is unknown, f^(n)(zeta) cannot be calculated. But we can bound * it and use the absolute value upper bound for estimates. For reference, * see Introduction to Numerical Analysis, ISBN 038795452X, chapter 2. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class DividedDifferenceInterpolatorTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/interpolation/NevilleInterpolatorTest.java b/src/test/java/org/apache/commons/math/analysis/interpolation/NevilleInterpolatorTest.java index a0453961f..a0d84dcc3 100644 --- a/src/test/java/org/apache/commons/math/analysis/interpolation/NevilleInterpolatorTest.java +++ b/src/test/java/org/apache/commons/math/analysis/interpolation/NevilleInterpolatorTest.java @@ -34,8 +34,8 @@ import junit.framework.TestCase; * Since zeta is unknown, f^(n)(zeta) cannot be calculated. But we can bound * it and use the absolute value upper bound for estimates. For reference, * see Introduction to Numerical Analysis, ISBN 038795452X, chapter 2. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class NevilleInterpolatorTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/interpolation/SplineInterpolatorTest.java b/src/test/java/org/apache/commons/math/analysis/interpolation/SplineInterpolatorTest.java index b7758fddc..a11cc60fc 100644 --- a/src/test/java/org/apache/commons/math/analysis/interpolation/SplineInterpolatorTest.java +++ b/src/test/java/org/apache/commons/math/analysis/interpolation/SplineInterpolatorTest.java @@ -29,16 +29,16 @@ import junit.framework.TestSuite; /** * Test the SplineInterpolator. * - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public class SplineInterpolatorTest extends TestCase { - + /** error tolerance for spline interpolator value at knot points */ protected double knotTolerance = 1E-12; - + /** error tolerance for interpolating polynomial coefficients */ protected double coefficientTolerance = 1E-6; - + /** error tolerance for interpolated values -- high value is from sin test */ protected double interpolationTolerance = 1E-2; @@ -60,14 +60,14 @@ public class SplineInterpolatorTest extends TestCase { UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); verifyConsistency((PolynomialSplineFunction) f, x); - + // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1d}; TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance); target = new double[]{y[1], 1d}; TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); - + // Check interpolation assertEquals(0.0,f.value(0.0), interpolationTolerance); assertEquals(0.4,f.value(0.4), interpolationTolerance); @@ -81,7 +81,7 @@ public class SplineInterpolatorTest extends TestCase { UnivariateRealInterpolator i = new SplineInterpolator(); UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); - + // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1d}; @@ -90,7 +90,7 @@ public class SplineInterpolatorTest extends TestCase { TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); target = new double[]{y[2], 1d}; TestUtils.assertEquals(polynomials[2].getCoefficients(), target, coefficientTolerance); - + // Check interpolation assertEquals(0,f.value(0), interpolationTolerance); assertEquals(1.4,f.value(1.4), interpolationTolerance); @@ -104,15 +104,15 @@ public class SplineInterpolatorTest extends TestCase { UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); verifyConsistency((PolynomialSplineFunction) f, x); - + // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1.5d, 0d, -2d}; TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance); target = new double[]{y[1], 0d, -3d, 2d}; - TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); + TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); } - + public void testInterpolateSin() throws Exception { double x[] = { @@ -130,15 +130,15 @@ public class SplineInterpolatorTest extends TestCase { UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); verifyConsistency((PolynomialSplineFunction) f, x); - + /* Check coefficients against values computed using R (version 1.8.1, Red Hat Linux 9) - * + * * To replicate in R: * x[1] <- 0 * x[2] <- pi / 6, etc, same for y[] (could use y <- scan() for y values) * g <- splinefun(x, y, "natural") * splinecoef <- eval(expression(z), envir = environment(g)) - * print(splinecoef) + * print(splinecoef) */ PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1.002676d, 0d, -0.17415829d}; @@ -156,13 +156,13 @@ public class SplineInterpolatorTest extends TestCase { target = new double[]{y[6], 3.466465e-16, 5.471344e-01, -0.08707914}; TestUtils.assertEquals(polynomials[6].getCoefficients(), target, coefficientTolerance); target = new double[]{y[7], 8.594367e-01, 2.735672e-01, -0.17415829}; - TestUtils.assertEquals(polynomials[7].getCoefficients(), target, coefficientTolerance); - + TestUtils.assertEquals(polynomials[7].getCoefficients(), target, coefficientTolerance); + //Check interpolation assertEquals(Math.sqrt(2d) / 2d,f.value(Math.PI/4d),interpolationTolerance); - assertEquals(Math.sqrt(2d) / 2d,f.value(3d*Math.PI/4d),interpolationTolerance); + assertEquals(Math.sqrt(2d) / 2d,f.value(3d*Math.PI/4d),interpolationTolerance); } - + public void testIllegalArguments() throws MathException { // Data set arrays of different size. @@ -183,32 +183,32 @@ public class SplineInterpolatorTest extends TestCase { } catch (IllegalArgumentException iae) { } } - + /** * verifies that f(x[i]) = y[i] for i = 0..n-1 where n is common length. */ - protected void verifyInterpolation(UnivariateRealFunction f, double x[], double y[]) + protected void verifyInterpolation(UnivariateRealFunction f, double x[], double y[]) throws Exception{ for (int i = 0; i < x.length; i++) { assertEquals(f.value(x[i]), y[i], knotTolerance); - } + } } - + /** * Verifies that interpolating polynomials satisfy consistency requirement: * adjacent polynomials must agree through two derivatives at knot points */ - protected void verifyConsistency(PolynomialSplineFunction f, double x[]) + protected void verifyConsistency(PolynomialSplineFunction f, double x[]) throws Exception { PolynomialFunction polynomials[] = f.getPolynomials(); for (int i = 1; i < x.length - 2; i++) { - // evaluate polynomials and derivatives at x[i + 1] - assertEquals(polynomials[i].value(x[i +1] - x[i]), polynomials[i + 1].value(0), 0.1); - assertEquals(polynomials[i].derivative().value(x[i +1] - x[i]), - polynomials[i + 1].derivative().value(0), 0.5); - assertEquals(polynomials[i].polynomialDerivative().derivative().value(x[i +1] - x[i]), - polynomials[i + 1].polynomialDerivative().derivative().value(0), 0.5); + // evaluate polynomials and derivatives at x[i + 1] + assertEquals(polynomials[i].value(x[i +1] - x[i]), polynomials[i + 1].value(0), 0.1); + assertEquals(polynomials[i].derivative().value(x[i +1] - x[i]), + polynomials[i + 1].derivative().value(0), 0.5); + assertEquals(polynomials[i].polynomialDerivative().derivative().value(x[i +1] - x[i]), + polynomials[i + 1].polynomialDerivative().derivative().value(0), 0.5); } } - + } diff --git a/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionLagrangeFormTest.java b/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionLagrangeFormTest.java index 0aea230f8..b362b17a3 100644 --- a/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionLagrangeFormTest.java +++ b/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionLagrangeFormTest.java @@ -26,7 +26,7 @@ import junit.framework.TestCase; * give us the exact same polynomial as result. Thus we can use a very * small tolerance to account only for round-off errors. * - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public final class PolynomialFunctionLagrangeFormTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionNewtonFormTest.java b/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionNewtonFormTest.java index d415e15e4..909ec84c5 100644 --- a/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionNewtonFormTest.java +++ b/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionNewtonFormTest.java @@ -24,7 +24,7 @@ import junit.framework.TestCase; *

      * The small tolerance number is used only to account for round-off errors. * - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public final class PolynomialFunctionNewtonFormTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionTest.java b/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionTest.java index 7f8224740..a43de4fb8 100644 --- a/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionTest.java +++ b/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialFunctionTest.java @@ -48,10 +48,10 @@ public final class PolynomialFunctionTest extends TestCase { assertEquals( f.value( -123.5), c[0], tolerance ); assertEquals( f.value( 3.0), c[0], tolerance ); assertEquals( f.value( 456.89), c[0], tolerance ); - + assertEquals(f.degree(), 0); assertEquals(f.derivative().value(0), 0, tolerance); - + assertEquals(f.polynomialDerivative().derivative().value(0), 0, tolerance); } @@ -59,7 +59,7 @@ public final class PolynomialFunctionTest extends TestCase { * tests the value of a linear polynomial. * *

      This will test the function f(x) = 3*x - 1.5

      - *

      This will have the values + *

      This will have the values * f(0.0) = -1.5, f(-1.0) = -4.5, f(-2.5) = -9.0, * f(0.5) = 0.0, f(1.5) = 3.0 and f(3.0) = 7.5 *

      @@ -77,11 +77,11 @@ public final class PolynomialFunctionTest extends TestCase { assertEquals( 0.0, f.value( 0.5), tolerance ); assertEquals( 3.0, f.value( 1.5), tolerance ); assertEquals( 7.5, f.value( 3.0), tolerance ); - + assertEquals(f.degree(), 1); - + assertEquals(f.polynomialDerivative().derivative().value(0), 0, tolerance); - + } @@ -103,12 +103,12 @@ public final class PolynomialFunctionTest extends TestCase { assertEquals( -2.0, f.value( 1.5), tolerance ); assertEquals( 7.0, f.value( -1.5), tolerance ); assertEquals( 265.5312, f.value( 12.34), tolerance ); - - } + + } - /** - * This will test the quintic function + /** + * This will test the quintic function * f(x) = x^2(x-5)(x+3)(x-1) = x^5 - 3x^4 -13x^3 + 15x^2

      * */ @@ -125,16 +125,16 @@ public final class PolynomialFunctionTest extends TestCase { assertEquals( 0.0, f.value( -3.0), tolerance ); assertEquals( 54.84375, f.value( -1.5), tolerance ); assertEquals( -8.06637, f.value( 1.3), tolerance ); - + assertEquals(f.degree(), 5); - - } + + } /** * tests the firstDerivative function by comparison * - *

      This will test the functions + *

      This will test the functions * f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6 * and h(x) = 6x - 4 */ @@ -230,7 +230,7 @@ public final class PolynomialFunctionTest extends TestCase { PolynomialFunction p2 = new PolynomialFunction(new double[] { 3.0, 2.0, 1.0 }); assertEquals(p2, TestUtils.serializeAndRecover(p2)); } - + public void checkPolynomial(PolynomialFunction p, String reference) { assertEquals(reference, p.toString()); } diff --git a/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialSplineFunctionTest.java b/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialSplineFunctionTest.java index 1bb39a1c2..e25d37076 100644 --- a/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialSplineFunctionTest.java +++ b/src/test/java/org/apache/commons/math/analysis/polynomials/PolynomialSplineFunctionTest.java @@ -31,52 +31,52 @@ public class PolynomialSplineFunctionTest extends TestCase { /** Error tolerance for tests */ protected double tolerance = 1.0e-12; - - /** - * Quadratic polynomials used in tests: - * + + /** + * Quadratic polynomials used in tests: + * * x^2 + x [-1, 0) * x^2 + x + 2 [0, 1) * x^2 + x + 4 [1, 2) - * + * * Defined so that evaluation using PolynomialSplineFunction evaluation * algorithm agrees at knot point boundaries. */ protected PolynomialFunction[] polynomials = { - new PolynomialFunction(new double[] {0d, 1d, 1d}), + new PolynomialFunction(new double[] {0d, 1d, 1d}), new PolynomialFunction(new double[] {2d, 1d, 1d}), new PolynomialFunction(new double[] {4d, 1d, 1d}) }; - + /** Knot points */ protected double[] knots = {-1, 0, 1, 2}; - + /** Derivative of test polynomials -- 2x + 1 */ - protected PolynomialFunction dp = + protected PolynomialFunction dp = new PolynomialFunction(new double[] {1d, 2d}); - - + + public void testConstructor() { - PolynomialSplineFunction spline = + PolynomialSplineFunction spline = new PolynomialSplineFunction(knots, polynomials); assertTrue(Arrays.equals(knots, spline.getKnots())); assertEquals(1d, spline.getPolynomials()[0].getCoefficients()[2], 0); assertEquals(3, spline.getN()); - + try { // too few knots new PolynomialSplineFunction(new double[] {0}, polynomials); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } - + try { // too many knots new PolynomialSplineFunction(new double[] {0,1,2,3,4}, polynomials); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } - + try { // knots not increasing new PolynomialSplineFunction(new double[] {0,1, 3, 2}, polynomials); fail("Expecting IllegalArgumentException"); @@ -84,15 +84,15 @@ public class PolynomialSplineFunctionTest extends TestCase { // expected } } - + public void testValues() throws Exception { - PolynomialSplineFunction spline = + PolynomialSplineFunction spline = new PolynomialSplineFunction(knots, polynomials); UnivariateRealFunction dSpline = spline.derivative(); - + /** * interior points -- spline value at x should equal p(x - knot) - * where knot is the largest knot point less than or equal to x and p + * where knot is the largest knot point less than or equal to x and p * is the polynomial defined over the knot segment to which x belongs. */ double x = -1; @@ -100,12 +100,12 @@ public class PolynomialSplineFunctionTest extends TestCase { for (int i = 0; i < 10; i++) { x+=0.25; index = findKnot(knots, x); - assertEquals("spline function evaluation failed for x=" + x, + assertEquals("spline function evaluation failed for x=" + x, polynomials[index].value(x - knots[index]), spline.value(x), tolerance); assertEquals("spline derivative evaluation failed for x=" + x, dp.value(x - knots[index]), dSpline.value(x), tolerance); } - + // knot points -- centering should zero arguments for (int i = 0; i < 3; i++) { assertEquals("spline function evaluation failed for knot=" + knots[i], @@ -113,22 +113,22 @@ public class PolynomialSplineFunctionTest extends TestCase { assertEquals("spline function evaluation failed for knot=" + knots[i], dp.value(0), dSpline.value(knots[i]), tolerance); } - + try { //outside of domain -- under min x = spline.value(-1.5); fail("Expecting IllegalArgumentException"); } catch (FunctionEvaluationException ex) { // expected } - + try { //outside of domain -- over max x = spline.value(2.5); fail("Expecting IllegalArgumentException"); } catch (FunctionEvaluationException ex) { // expected - } - } - + } + } + /** * Do linear search to find largest knot point less than or equal to x. * Implementation does binary search. @@ -145,4 +145,4 @@ public class PolynomialSplineFunctionTest extends TestCase { throw new IllegalArgumentException("x is out of range"); } } - + diff --git a/src/test/java/org/apache/commons/math/analysis/solvers/BisectionSolverTest.java b/src/test/java/org/apache/commons/math/analysis/solvers/BisectionSolverTest.java index 62aef5071..d0fcafd82 100644 --- a/src/test/java/org/apache/commons/math/analysis/solvers/BisectionSolverTest.java +++ b/src/test/java/org/apache/commons/math/analysis/solvers/BisectionSolverTest.java @@ -32,7 +32,7 @@ public final class BisectionSolverTest extends TestCase { public void testDeprecated() throws MathException { UnivariateRealFunction f = new SinFunction(); double result; - + UnivariateRealSolver solver = new BisectionSolver(f); result = solver.solve(3, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); @@ -44,7 +44,7 @@ public final class BisectionSolverTest extends TestCase { public void testSinZero() throws MathException { UnivariateRealFunction f = new SinFunction(); double result; - + UnivariateRealSolver solver = new BisectionSolver(); result = solver.solve(f, 3, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); @@ -90,67 +90,67 @@ public final class BisectionSolverTest extends TestCase { result = solver.solve(f, 0.85, 5); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); - + assertEquals(result, solver.getResult(), 0); assertTrue(solver.getIterationCount() > 0); } - + /** - * + * */ public void testSetFunctionValueAccuracy(){ - double expected = 1.0e-2; + double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setFunctionValueAccuracy(expected); assertEquals(expected, solver.getFunctionValueAccuracy(), 1.0e-2); - } - + } + /** - * + * */ public void testResetFunctionValueAccuracy(){ - double newValue = 1.0e-2; + double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getFunctionValueAccuracy(); solver.setFunctionValueAccuracy(newValue); solver.resetFunctionValueAccuracy(); assertEquals(oldValue, solver.getFunctionValueAccuracy(), 1.0e-2); - } - + } + /** - * + * */ public void testSetAbsoluteAccuracy(){ - double expected = 1.0e-2; + double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setAbsoluteAccuracy(expected); - assertEquals(expected, solver.getAbsoluteAccuracy(), 1.0e-2); - } - + assertEquals(expected, solver.getAbsoluteAccuracy(), 1.0e-2); + } + /** - * + * */ public void testResetAbsoluteAccuracy(){ - double newValue = 1.0e-2; + double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getAbsoluteAccuracy(); solver.setAbsoluteAccuracy(newValue); solver.resetAbsoluteAccuracy(); assertEquals(oldValue, solver.getAbsoluteAccuracy(), 1.0e-2); - } - + } + /** - * + * */ public void testSetMaximalIterationCount(){ int expected = 100; UnivariateRealSolver solver = new BisectionSolver(); solver.setMaximalIterationCount(expected); assertEquals(expected, solver.getMaximalIterationCount()); - } - + } + /** - * + * */ public void testResetMaximalIterationCount(){ int newValue = 10000; @@ -159,29 +159,29 @@ public final class BisectionSolverTest extends TestCase { solver.setMaximalIterationCount(newValue); solver.resetMaximalIterationCount(); assertEquals(oldValue, solver.getMaximalIterationCount()); - } - + } + /** - * + * */ public void testSetRelativeAccuracy(){ double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setRelativeAccuracy(expected); assertEquals(expected, solver.getRelativeAccuracy(), 1.0e-2); - } - + } + /** - * + * */ public void testResetRelativeAccuracy(){ - double newValue = 1.0e-2; + double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getRelativeAccuracy(); solver.setRelativeAccuracy(newValue); solver.resetRelativeAccuracy(); assertEquals(oldValue, solver.getRelativeAccuracy(), 1.0e-2); - } - - + } + + } diff --git a/src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java b/src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java index d1c36e34e..18ebe8546 100644 --- a/src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java +++ b/src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -34,8 +34,8 @@ import junit.framework.TestSuite; * regressions. On average Brent-Dekker should use 4..5 iterations for the * default absolute accuracy of 10E-8 for sinus and the quintic function around * zero, and 5..10 iterations for the other zeros. - * - * @version $Revision:670469 $ $Date:2008-06-23 10:01:38 +0200 (lun., 23 juin 2008) $ + * + * @version $Revision:670469 $ $Date:2008-06-23 10:01:38 +0200 (lun., 23 juin 2008) $ */ public final class BrentSolverTest extends TestCase { @@ -53,7 +53,7 @@ public final class BrentSolverTest extends TestCase { public void testDeprecated() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will - // still converge quadratically. + // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(f); @@ -90,7 +90,7 @@ public final class BrentSolverTest extends TestCase { public void testSinZero() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will - // still converge quadratically. + // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(); @@ -309,11 +309,11 @@ public final class BrentSolverTest extends TestCase { result = UnivariateRealSolverUtils.solve(f, 0.85, 5); assertEquals(result, 1.0, 1E-6); } - + public void testRootEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); - + // endpoint is root double result = solver.solve(f, Math.PI, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); @@ -321,7 +321,7 @@ public final class BrentSolverTest extends TestCase { result = solver.solve(f, 3, Math.PI); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); } - + public void testBadEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); @@ -350,7 +350,7 @@ public final class BrentSolverTest extends TestCase { assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); int referenceCallsCount = f.getCallsCount(); assertTrue(referenceCallsCount >= 13); - + // invalid guess (it *is* a root, but outside of the range) try { result = solver.solve(f, 0.6, 7.0, 0.0); @@ -360,13 +360,13 @@ public final class BrentSolverTest extends TestCase { } catch (Exception e) { fail("wrong exception caught: " + e.getMessage()); } - + // bad guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.61); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() > referenceCallsCount); - + // good guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.999999); @@ -379,7 +379,7 @@ public final class BrentSolverTest extends TestCase { assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertEquals(0, solver.getIterationCount()); assertEquals(1, f.getCallsCount()); - + } - + } diff --git a/src/test/java/org/apache/commons/math/analysis/solvers/LaguerreSolverTest.java b/src/test/java/org/apache/commons/math/analysis/solvers/LaguerreSolverTest.java index 745a2d56f..689d0b75a 100644 --- a/src/test/java/org/apache/commons/math/analysis/solvers/LaguerreSolverTest.java +++ b/src/test/java/org/apache/commons/math/analysis/solvers/LaguerreSolverTest.java @@ -30,8 +30,8 @@ import junit.framework.TestCase; * show that for a default absolute accuracy of 1E-6, it generally takes * less than 5 iterations to find one root, provided solveAll() is not * invoked, and 15 to 20 iterations to find all roots for quintic function. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class LaguerreSolverTest extends TestCase { @@ -157,7 +157,7 @@ public final class LaguerreSolverTest extends TestCase { tolerance = Math.max(solver.getAbsoluteAccuracy(), Math.abs(expected.abs() * solver.getRelativeAccuracy())); TestUtils.assertContains(result, expected, tolerance); - + expected = new Complex(0.5, -0.5 * Math.sqrt(3.0)); tolerance = Math.max(solver.getAbsoluteAccuracy(), Math.abs(expected.abs() * solver.getRelativeAccuracy())); diff --git a/src/test/java/org/apache/commons/math/analysis/solvers/MullerSolverTest.java b/src/test/java/org/apache/commons/math/analysis/solvers/MullerSolverTest.java index 56e08f17b..0fd61212e 100644 --- a/src/test/java/org/apache/commons/math/analysis/solvers/MullerSolverTest.java +++ b/src/test/java/org/apache/commons/math/analysis/solvers/MullerSolverTest.java @@ -34,8 +34,8 @@ import junit.framework.TestCase; *

      * Tests for the exponential function illustrate the situations where * Muller solver performs poorly. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class MullerSolverTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/solvers/NewtonSolverTest.java b/src/test/java/org/apache/commons/math/analysis/solvers/NewtonSolverTest.java index 05f5418bc..6b788916e 100644 --- a/src/test/java/org/apache/commons/math/analysis/solvers/NewtonSolverTest.java +++ b/src/test/java/org/apache/commons/math/analysis/solvers/NewtonSolverTest.java @@ -33,14 +33,14 @@ public final class NewtonSolverTest extends TestCase { public void testDeprecated() throws MathException { DifferentiableUnivariateRealFunction f = new SinFunction(); double result; - + UnivariateRealSolver solver = new NewtonSolver(f); result = solver.solve(3, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); result = solver.solve(1, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); - + assertEquals(result, solver.getResult(), 0); assertTrue(solver.getIterationCount() > 0); } @@ -51,14 +51,14 @@ public final class NewtonSolverTest extends TestCase { public void testSinZero() throws MathException { DifferentiableUnivariateRealFunction f = new SinFunction(); double result; - + UnivariateRealSolver solver = new NewtonSolver(); result = solver.solve(f, 3, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); result = solver.solve(f, 1, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); - + assertEquals(result, solver.getResult(), 0); assertTrue(solver.getIterationCount() > 0); } @@ -104,5 +104,5 @@ public final class NewtonSolverTest extends TestCase { result = solver.solve(f, 0.85, 5); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); } - + } diff --git a/src/test/java/org/apache/commons/math/analysis/solvers/RiddersSolverTest.java b/src/test/java/org/apache/commons/math/analysis/solvers/RiddersSolverTest.java index 1b4774f96..07c971f76 100644 --- a/src/test/java/org/apache/commons/math/analysis/solvers/RiddersSolverTest.java +++ b/src/test/java/org/apache/commons/math/analysis/solvers/RiddersSolverTest.java @@ -32,8 +32,8 @@ import junit.framework.TestCase; * accuracy of 1E-6, it generally takes less than 5 iterations for close * initial bracket and 5 to 10 iterations for distant initial bracket * to converge. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class RiddersSolverTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/analysis/solvers/UnivariateRealSolverFactoryImplTest.java b/src/test/java/org/apache/commons/math/analysis/solvers/UnivariateRealSolverFactoryImplTest.java index 726235142..25d1e1139 100644 --- a/src/test/java/org/apache/commons/math/analysis/solvers/UnivariateRealSolverFactoryImplTest.java +++ b/src/test/java/org/apache/commons/math/analysis/solvers/UnivariateRealSolverFactoryImplTest.java @@ -24,10 +24,10 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class UnivariateRealSolverFactoryImplTest extends TestCase { - + /** solver factory */ private UnivariateRealSolverFactory factory; - + /** * @throws java.lang.Exception * @see junit.framework.TestCase#tearDown() @@ -37,7 +37,7 @@ public class UnivariateRealSolverFactoryImplTest extends TestCase { super.setUp(); factory = new UnivariateRealSolverFactoryImpl(); } - + /** * @throws java.lang.Exception * @see junit.framework.TestCase#tearDown() diff --git a/src/test/java/org/apache/commons/math/analysis/solvers/UnivariateRealSolverUtilsTest.java b/src/test/java/org/apache/commons/math/analysis/solvers/UnivariateRealSolverUtilsTest.java index e606b40af..b08d1c54f 100644 --- a/src/test/java/org/apache/commons/math/analysis/solvers/UnivariateRealSolverUtilsTest.java +++ b/src/test/java/org/apache/commons/math/analysis/solvers/UnivariateRealSolverUtilsTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,9 +27,9 @@ import org.apache.commons.math.analysis.UnivariateRealFunction; * @version $Revision$ $Date$ */ public class UnivariateRealSolverUtilsTest extends TestCase { - + protected UnivariateRealFunction sin = new SinFunction(); - + public void testSolveNull() throws MathException { try { UnivariateRealSolverUtils.solve(null, 0.0, 4.0); @@ -38,25 +38,25 @@ public class UnivariateRealSolverUtilsTest extends TestCase { // success } } - + public void testSolveBadParameters() throws MathException { try { // bad endpoints - UnivariateRealSolverUtils.solve(sin,0.0, 4.0, 4.0); + UnivariateRealSolverUtils.solve(sin,0.0, 4.0, 4.0); } catch (IllegalArgumentException ex) { // expected - } + } try { // bad accuracy - UnivariateRealSolverUtils.solve(sin, 0.0, 4.0, 0.0); + UnivariateRealSolverUtils.solve(sin, 0.0, 4.0, 0.0); } catch (IllegalArgumentException ex) { // expected - } + } } - - public void testSolveSin() throws MathException { + + public void testSolveSin() throws MathException { double x = UnivariateRealSolverUtils.solve(sin, 1.0, 4.0); assertEquals(Math.PI, x, 1.0e-4); } - + public void testSolveAccuracyNull() throws MathException { try { double accuracy = 1.0e-6; @@ -66,36 +66,36 @@ public class UnivariateRealSolverUtilsTest extends TestCase { // success } } - + public void testSolveAccuracySin() throws MathException { double accuracy = 1.0e-6; double x = UnivariateRealSolverUtils.solve(sin, 1.0, 4.0, accuracy); assertEquals(Math.PI, x, accuracy); } - + public void testSolveNoRoot() throws MathException { try { - UnivariateRealSolverUtils.solve(sin, 1.0, 1.5); - fail("Expecting IllegalArgumentException "); + UnivariateRealSolverUtils.solve(sin, 1.0, 1.5); + fail("Expecting IllegalArgumentException "); } catch (IllegalArgumentException ex) { // expected } } - + public void testBracketSin() throws MathException { - double[] result = UnivariateRealSolverUtils.bracket(sin, + double[] result = UnivariateRealSolverUtils.bracket(sin, 0.0, -2.0, 2.0); assertTrue(sin.value(result[0]) < 0); assertTrue(sin.value(result[1]) > 0); } - + public void testBracketEndpointRoot() throws MathException { double[] result = UnivariateRealSolverUtils.bracket(sin, 1.5, 0, 2.0); assertEquals(0.0, sin.value(result[0]), 1.0e-15); assertTrue(sin.value(result[1]) > 0); } - + public void testBadParameters() throws MathException { try { // null function UnivariateRealSolverUtils.bracket(null, 1.5, 0, 2.0); @@ -120,7 +120,7 @@ public class UnivariateRealSolverUtilsTest extends TestCase { fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } } - + } diff --git a/src/test/java/org/apache/commons/math/complex/ComplexFormatAbstractTest.java b/src/test/java/org/apache/commons/math/complex/ComplexFormatAbstractTest.java index 8ecbe8788..e54fc2617 100644 --- a/src/test/java/org/apache/commons/math/complex/ComplexFormatAbstractTest.java +++ b/src/test/java/org/apache/commons/math/complex/ComplexFormatAbstractTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,7 +27,7 @@ import org.apache.commons.math.util.CompositeFormat; import junit.framework.TestCase; public abstract class ComplexFormatAbstractTest extends TestCase { - + CompositeFormat complexFormat = null; ComplexFormat complexFormatJ = null; @@ -41,108 +41,108 @@ public abstract class ComplexFormatAbstractTest extends TestCase { complexFormatJ = ComplexFormat.getInstance(getLocale()); complexFormatJ.setImaginaryCharacter("j"); } - + public void testSimpleNoDecimals() { Complex c = new Complex(1, 1); String expected = "1 + 1i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testSimpleWithDecimals() { Complex c = new Complex(1.23, 1.43); String expected = "1" + getDecimalCharacter() + "23 + 1" + getDecimalCharacter() + "43i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testSimpleWithDecimalsTrunc() { Complex c = new Complex(1.2323, 1.4343); String expected = "1" + getDecimalCharacter() + "23 + 1" + getDecimalCharacter() + "43i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testNegativeReal() { Complex c = new Complex(-1.2323, 1.4343); String expected = "-1" + getDecimalCharacter() + "23 + 1" + getDecimalCharacter() + "43i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testNegativeImaginary() { Complex c = new Complex(1.2323, -1.4343); String expected = "1" + getDecimalCharacter() + "23 - 1" + getDecimalCharacter() + "43i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testNegativeBoth() { Complex c = new Complex(-1.2323, -1.4343); String expected = "-1" + getDecimalCharacter() + "23 - 1" + getDecimalCharacter() + "43i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testZeroReal() { Complex c = new Complex(0.0, -1.4343); String expected = "0 - 1" + getDecimalCharacter() + "43i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testZeroImaginary() { Complex c = new Complex(30.233, 0); String expected = "30" + getDecimalCharacter() + "23"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testDifferentImaginaryChar() { Complex c = new Complex(1, 1); String expected = "1 + 1j"; - String actual = complexFormatJ.format(c); + String actual = complexFormatJ.format(c); assertEquals(expected, actual); } - + public void testStaticFormatComplex() { Locale defaultLocal = Locale.getDefault(); Locale.setDefault(getLocale()); - + Complex c = new Complex(232.222, -342.33); String expected = "232" + getDecimalCharacter() + "22 - 342" + getDecimalCharacter() + "33i"; - String actual = ComplexFormat.formatComplex(c); + String actual = ComplexFormat.formatComplex(c); assertEquals(expected, actual); - + Locale.setDefault(defaultLocal); } public void testNan() { Complex c = new Complex(Double.NaN, Double.NaN); String expected = "(NaN) + (NaN)i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testPositiveInfinity() { Complex c = new Complex(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); String expected = "(Infinity) + (Infinity)i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } public void testNegativeInfinity() { Complex c = new Complex(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); String expected = "(-Infinity) - (Infinity)i"; - String actual = complexFormat.format(c); + String actual = complexFormat.format(c); assertEquals(expected, actual); } - + public void testParseSimpleNoDecimals() { String source = "1 + 1i"; Complex expected = new Complex(1, 1); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -153,7 +153,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "1" + getDecimalCharacter() + "23 + 1" + getDecimalCharacter() + "43i"; Complex expected = new Complex(1.23, 1.43); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -164,7 +164,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "1" + getDecimalCharacter() + "2323 + 1" + getDecimalCharacter() + "4343i"; Complex expected = new Complex(1.2323, 1.4343); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -175,7 +175,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "-1" + getDecimalCharacter() + "2323 + 1" + getDecimalCharacter() + "4343i"; Complex expected = new Complex(-1.2323, 1.4343); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -186,7 +186,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "1" + getDecimalCharacter() + "2323 - 1" + getDecimalCharacter() + "4343i"; Complex expected = new Complex(1.2323, -1.4343); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -197,7 +197,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "-1" + getDecimalCharacter() + "2323 - 1" + getDecimalCharacter() + "4343i"; Complex expected = new Complex(-1.2323, -1.4343); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -208,7 +208,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "0" + getDecimalCharacter() + "0 - 1" + getDecimalCharacter() + "4343i"; Complex expected = new Complex(0.0, -1.4343); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -219,7 +219,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "-1" + getDecimalCharacter() + "2323"; Complex expected = new Complex(-1.2323, 0); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -230,18 +230,18 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "-1" + getDecimalCharacter() + "2323 - 1" + getDecimalCharacter() + "4343j"; Complex expected = new Complex(-1.2323, -1.4343); try { - Complex actual = (Complex)complexFormatJ.parseObject(source); + Complex actual = (Complex)complexFormatJ.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); } } - + public void testParseNan() { String source = "(NaN) + (NaN)i"; Complex expected = new Complex(Double.NaN, Double.NaN); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -252,7 +252,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "(Infinity) + (Infinity)i"; Complex expected = new Complex(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -263,29 +263,29 @@ public abstract class ComplexFormatAbstractTest extends TestCase { String source = "(-Infinity) - (Infinity)i"; Complex expected = new Complex(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); try { - Complex actual = (Complex)complexFormat.parseObject(source); + Complex actual = (Complex)complexFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); } } - + public void testConstructorSingleFormat() { NumberFormat nf = NumberFormat.getInstance(); ComplexFormat cf = new ComplexFormat(nf); assertNotNull(cf); assertEquals(nf, cf.getRealFormat()); } - + public void testGetImaginaryFormat() { NumberFormat nf = NumberFormat.getInstance(); ComplexFormat cf = new ComplexFormat(); - + assertNotSame(nf, cf.getImaginaryFormat()); cf.setImaginaryFormat(nf); assertSame(nf, cf.getImaginaryFormat()); } - + public void testSetImaginaryFormatNull() { try { ComplexFormat cf = new ComplexFormat(); @@ -295,7 +295,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { // success } } - + public void testSetRealFormatNull() { try { ComplexFormat cf = new ComplexFormat(); @@ -305,16 +305,16 @@ public abstract class ComplexFormatAbstractTest extends TestCase { // success } } - + public void testGetRealFormat() { NumberFormat nf = NumberFormat.getInstance(); ComplexFormat cf = new ComplexFormat(); - + assertNotSame(nf, cf.getRealFormat()); cf.setRealFormat(nf); assertSame(nf, cf.getRealFormat()); } - + public void testSetImaginaryCharacterNull() { try { ComplexFormat cf = new ComplexFormat(); @@ -324,7 +324,7 @@ public abstract class ComplexFormatAbstractTest extends TestCase { // success } } - + public void testSetImaginaryCharacterEmpty() { try { ComplexFormat cf = new ComplexFormat(); @@ -334,14 +334,14 @@ public abstract class ComplexFormatAbstractTest extends TestCase { // success } } - + public void testFormatNumber() { CompositeFormat cf = ComplexFormat.getInstance(getLocale()); Double pi = Double.valueOf(Math.PI); String text = cf.format(pi); assertEquals("3" + getDecimalCharacter() + "14", text); } - + public void testFormatObject() { try { CompositeFormat cf = new ComplexFormat(); diff --git a/src/test/java/org/apache/commons/math/complex/ComplexFormatTest.java b/src/test/java/org/apache/commons/math/complex/ComplexFormatTest.java index 263eb3300..5ae92995c 100644 --- a/src/test/java/org/apache/commons/math/complex/ComplexFormatTest.java +++ b/src/test/java/org/apache/commons/math/complex/ComplexFormatTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ public class ComplexFormatTest extends ComplexFormatAbstractTest { protected char getDecimalCharacter() { return '.'; } - + @Override protected Locale getLocale() { return Locale.US; diff --git a/src/test/java/org/apache/commons/math/complex/ComplexTest.java b/src/test/java/org/apache/commons/math/complex/ComplexTest.java index 97cf65b0a..cd9b15ec9 100644 --- a/src/test/java/org/apache/commons/math/complex/ComplexTest.java +++ b/src/test/java/org/apache/commons/math/complex/ComplexTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,7 +27,7 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class ComplexTest extends TestCase { - + private double inf = Double.POSITIVE_INFINITY; private double neginf = Double.NEGATIVE_INFINITY; @@ -51,13 +51,13 @@ public class ComplexTest extends TestCase { private Complex nanInf = new Complex(nan, inf); private Complex nanNegInf = new Complex(nan, neginf); private Complex nanZero = new Complex(nan, 0); - + public void testConstructor() { Complex z = new Complex(3.0, 4.0); assertEquals(3.0, z.getReal(), 1.0e-5); assertEquals(4.0, z.getImaginary(), 1.0e-5); } - + public void testConstructorNaN() { Complex z = new Complex(3.0, Double.NaN); assertTrue(z.isNaN()); @@ -68,27 +68,27 @@ public class ComplexTest extends TestCase { z = new Complex(3.0, 4.0); assertFalse(z.isNaN()); } - + public void testAbs() { Complex z = new Complex(3.0, 4.0); assertEquals(5.0, z.abs(), 1.0e-5); } - + public void testAbsNaN() { assertTrue(Double.isNaN(Complex.NaN.abs())); Complex z = new Complex(inf, nan); assertTrue(Double.isNaN(z.abs())); } - + public void testAbsInfinite() { Complex z = new Complex(inf, 0); assertEquals(inf, z.abs(), 0); z = new Complex(0, neginf); assertEquals(inf, z.abs(), 0); z = new Complex(inf, neginf); - assertEquals(inf, z.abs(), 0); + assertEquals(inf, z.abs(), 0); } - + public void testAdd() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); @@ -96,7 +96,7 @@ public class ComplexTest extends TestCase { assertEquals(8.0, z.getReal(), 1.0e-5); assertEquals(10.0, z.getImaginary(), 1.0e-5); } - + public void testAddNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.add(Complex.NaN); @@ -106,37 +106,37 @@ public class ComplexTest extends TestCase { assertEquals(w.getReal(), 4.0, 0); assertTrue(Double.isNaN(w.getImaginary())); } - + public void testAddInfinite() { Complex x = new Complex(1, 1); Complex z = new Complex(inf, 0); Complex w = x.add(z); assertEquals(w.getImaginary(), 1, 0); assertEquals(inf, w.getReal(), 0); - + x = new Complex(neginf, 0); assertTrue(Double.isNaN(x.add(z).getReal())); } - + public void testConjugate() { Complex x = new Complex(3.0, 4.0); Complex z = x.conjugate(); assertEquals(3.0, z.getReal(), 1.0e-5); assertEquals(-4.0, z.getImaginary(), 1.0e-5); } - + public void testConjugateNaN() { Complex z = Complex.NaN.conjugate(); assertTrue(z.isNaN()); } - + public void testConjugateInfiinite() { Complex z = new Complex(0, inf); assertEquals(neginf, z.conjugate().getImaginary(), 0); z = new Complex(0, neginf); assertEquals(inf, z.conjugate().getImaginary(), 0); } - + public void testDivide() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); @@ -144,47 +144,47 @@ public class ComplexTest extends TestCase { assertEquals(39.0 / 61.0, z.getReal(), 1.0e-5); assertEquals(2.0 / 61.0, z.getImaginary(), 1.0e-5); } - + public void testDivideInfinite() { Complex x = new Complex(3, 4); Complex w = new Complex(neginf, inf); assertTrue(x.divide(w).equals(Complex.ZERO)); - + Complex z = w.divide(x); assertTrue(Double.isNaN(z.getReal())); assertEquals(inf, z.getImaginary(), 0); - + w = new Complex(inf, inf); z = w.divide(x); assertTrue(Double.isNaN(z.getImaginary())); assertEquals(inf, z.getReal(), 0); - + w = new Complex(1, inf); z = w.divide(w); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); } - + public void testDivideNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.NaN); assertTrue(z.isNaN()); } - - public void testDivideNaNInf() { + + public void testDivideNaNInf() { Complex z = oneInf.divide(Complex.ONE); assertTrue(Double.isNaN(z.getReal())); assertEquals(inf, z.getImaginary(), 0); - + z = negInfNegInf.divide(oneNaN); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); - + z = negInfInf.divide(Complex.ONE); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); } - + public void testMultiply() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); @@ -192,13 +192,13 @@ public class ComplexTest extends TestCase { assertEquals(-9.0, z.getReal(), 1.0e-5); assertEquals(38.0, z.getImaginary(), 1.0e-5); } - + public void testMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Complex.NaN); assertTrue(z.isNaN()); } - + public void testMultiplyNaNInf() { Complex z = new Complex(1,1); Complex w = z.multiply(infOne); @@ -209,16 +209,16 @@ public class ComplexTest extends TestCase { assertTrue(new Complex( 1,0).multiply(infInf).equals(Complex.INF)); assertTrue(new Complex(-1,0).multiply(infInf).equals(Complex.INF)); assertTrue(new Complex( 1,0).multiply(negInfZero).equals(Complex.INF)); - + w = oneInf.multiply(oneNegInf); assertEquals(w.getReal(), inf, 0); assertEquals(w.getImaginary(), inf, 0); - + w = negInfNegInf.multiply(oneNaN); assertTrue(Double.isNaN(w.getReal())); - assertTrue(Double.isNaN(w.getImaginary())); + assertTrue(Double.isNaN(w.getImaginary())); } - + public void testScalarMultiply() { Complex x = new Complex(3.0, 4.0); double y = 2.0; @@ -226,13 +226,13 @@ public class ComplexTest extends TestCase { assertEquals(6.0, z.getReal(), 1.0e-5); assertEquals(8.0, z.getImaginary(), 1.0e-5); } - + public void testScalarMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Double.NaN); assertTrue(z.isNaN()); } - + public void testScalarMultiplyInf() { Complex z = new Complex(1,1); Complex w = z.multiply(Double.POSITIVE_INFINITY); @@ -243,19 +243,19 @@ public class ComplexTest extends TestCase { assertEquals(w.getReal(), inf, 0); assertEquals(w.getImaginary(), inf, 0); } - + public void testNegate() { Complex x = new Complex(3.0, 4.0); Complex z = x.negate(); assertEquals(-3.0, z.getReal(), 1.0e-5); assertEquals(-4.0, z.getImaginary(), 1.0e-5); } - + public void testNegateNaN() { Complex z = Complex.NaN.negate(); assertTrue(z.isNaN()); } - + public void testSubtract() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); @@ -263,46 +263,46 @@ public class ComplexTest extends TestCase { assertEquals(-2.0, z.getReal(), 1.0e-5); assertEquals(-2.0, z.getImaginary(), 1.0e-5); } - + public void testSubtractNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.subtract(Complex.NaN); assertTrue(z.isNaN()); } - + public void testEqualsNull() { Complex x = new Complex(3.0, 4.0); assertFalse(x.equals(null)); } - + public void testEqualsClass() { Complex x = new Complex(3.0, 4.0); assertFalse(x.equals(this)); } - + public void testEqualsSame() { Complex x = new Complex(3.0, 4.0); assertTrue(x.equals(x)); } - + public void testEqualsTrue() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(3.0, 4.0); assertTrue(x.equals(y)); } - + public void testEqualsRealDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0 + Double.MIN_VALUE, 0.0); assertFalse(x.equals(y)); } - + public void testEqualsImaginaryDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); assertFalse(x.equals(y)); } - + public void testEqualsNaN() { Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); @@ -311,7 +311,7 @@ public class ComplexTest extends TestCase { assertTrue(imaginaryNaN.equals(complexNaN)); assertTrue(realNaN.equals(complexNaN)); } - + public void testHashCode() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); @@ -323,15 +323,15 @@ public class ComplexTest extends TestCase { assertEquals(realNaN.hashCode(), imaginaryNaN.hashCode()); assertEquals(imaginaryNaN.hashCode(), Complex.NaN.hashCode()); } - + public void testAcos() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.936812, -2.30551); TestUtils.assertEquals(expected, z.acos(), 1.0e-5); - TestUtils.assertEquals(new Complex(Math.acos(0), 0), + TestUtils.assertEquals(new Complex(Math.acos(0), 0), Complex.ZERO.acos(), 1.0e-12); } - + public void testAcosInf() { TestUtils.assertSame(Complex.NaN, oneInf.acos()); TestUtils.assertSame(Complex.NaN, oneNegInf.acos()); @@ -342,21 +342,21 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, negInfInf.acos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.acos()); } - + public void testAcosNaN() { assertTrue(Complex.NaN.acos().isNaN()); } - + public void testAsin() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.633984, 2.30551); TestUtils.assertEquals(expected, z.asin(), 1.0e-5); } - + public void testAsinNaN() { assertTrue(Complex.NaN.asin().isNaN()); } - + public void testAsinInf() { TestUtils.assertSame(Complex.NaN, oneInf.asin()); TestUtils.assertSame(Complex.NaN, oneNegInf.asin()); @@ -367,14 +367,14 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, negInfInf.asin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.asin()); } - - + + public void testAtan() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.44831, 0.158997); TestUtils.assertEquals(expected, z.atan(), 1.0e-5); } - + public void testAtanInf() { TestUtils.assertSame(Complex.NaN, oneInf.atan()); TestUtils.assertSame(Complex.NaN, oneNegInf.atan()); @@ -384,23 +384,23 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, infNegInf.atan()); TestUtils.assertSame(Complex.NaN, negInfInf.atan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.atan()); - } - + } + public void testAtanNaN() { assertTrue(Complex.NaN.atan().isNaN()); assertTrue(Complex.I.atan().isNaN()); } - + public void testCos() { Complex z = new Complex(3, 4); Complex expected = new Complex(-27.03495, -3.851153); TestUtils.assertEquals(expected, z.cos(), 1.0e-5); } - + public void testCosNaN() { assertTrue(Complex.NaN.cos().isNaN()); } - + public void testCosInf() { TestUtils.assertSame(infNegInf, oneInf.cos()); TestUtils.assertSame(infInf, oneNegInf.cos()); @@ -410,19 +410,19 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, infNegInf.cos()); TestUtils.assertSame(Complex.NaN, negInfInf.cos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cos()); - } - + } + public void testCosh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.58066, -7.58155); TestUtils.assertEquals(expected, z.cosh(), 1.0e-5); } - + public void testCoshNaN() { assertTrue(Complex.NaN.cosh().isNaN()); } - - public void testCoshInf() { + + public void testCoshInf() { TestUtils.assertSame(Complex.NaN, oneInf.cosh()); TestUtils.assertSame(Complex.NaN, oneNegInf.cosh()); TestUtils.assertSame(infInf, infOne.cosh()); @@ -431,23 +431,23 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, infNegInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cosh()); - } - + } + public void testExp() { Complex z = new Complex(3, 4); Complex expected = new Complex(-13.12878, -15.20078); TestUtils.assertEquals(expected, z.exp(), 1.0e-5); - TestUtils.assertEquals(Complex.ONE, + TestUtils.assertEquals(Complex.ONE, Complex.ZERO.exp(), 10e-12); Complex iPi = Complex.I.multiply(new Complex(pi,0)); - TestUtils.assertEquals(Complex.ONE.negate(), + TestUtils.assertEquals(Complex.ONE.negate(), iPi.exp(), 10e-12); } - + public void testExpNaN() { assertTrue(Complex.NaN.exp().isNaN()); } - + public void testExpInf() { TestUtils.assertSame(Complex.NaN, oneInf.exp()); TestUtils.assertSame(Complex.NaN, oneNegInf.exp()); @@ -458,17 +458,17 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, negInfInf.exp()); TestUtils.assertSame(Complex.NaN, negInfNegInf.exp()); } - + public void testLog() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.60944, 0.927295); TestUtils.assertEquals(expected, z.log(), 1.0e-5); } - + public void testLogNaN() { assertTrue(Complex.NaN.log().isNaN()); } - + public void testLogInf() { TestUtils.assertEquals(new Complex(inf, pi / 2), oneInf.log(), 10e-12); @@ -486,28 +486,28 @@ public class ComplexTest extends TestCase { TestUtils.assertEquals(new Complex(inf, - 3d * pi / 4), negInfNegInf.log(), 10e-12); } - + public void testLogZero() { TestUtils.assertSame(negInfZero, Complex.ZERO.log()); } - + public void testPow() { Complex x = new Complex(3, 4); Complex y = new Complex(5, 6); Complex expected = new Complex(-1.860893, 11.83677); TestUtils.assertEquals(expected, x.pow(y), 1.0e-5); } - + public void testPowNaNBase() { Complex x = new Complex(3, 4); assertTrue(Complex.NaN.pow(x).isNaN()); } - + public void testPowNaNExponent() { Complex x = new Complex(3, 4); assertTrue(x.pow(Complex.NaN).isNaN()); } - + public void testPowInf() { TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneNegInf)); @@ -530,15 +530,15 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN,infInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(negInfNegInf)); - TestUtils.assertSame(Complex.NaN,infNegInf.pow(infInf)); + TestUtils.assertSame(Complex.NaN,infNegInf.pow(infInf)); } - + public void testPowZero() { - TestUtils.assertSame(Complex.NaN, + TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ONE)); - TestUtils.assertSame(Complex.NaN, + TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ZERO)); - TestUtils.assertSame(Complex.NaN, + TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.I)); TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(Complex.ZERO), 10e-12); @@ -547,22 +547,22 @@ public class ComplexTest extends TestCase { TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(Complex.ZERO), 10e-12); } - + public void testpowNull() { try { - Complex.ONE.pow(null); + Complex.ONE.pow(null); fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected } } - + public void testSin() { Complex z = new Complex(3, 4); Complex expected = new Complex(3.853738, -27.01681); TestUtils.assertEquals(expected, z.sin(), 1.0e-5); } - + public void testSinInf() { TestUtils.assertSame(infInf, oneInf.sin()); TestUtils.assertSame(infNegInf, oneNegInf.sin()); @@ -573,21 +573,21 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, negInfInf.sin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sin()); } - + public void testSinNaN() { assertTrue(Complex.NaN.sin().isNaN()); } - + public void testSinh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.54812, -7.61923); TestUtils.assertEquals(expected, z.sinh(), 1.0e-5); } - + public void testSinhNaN() { assertTrue(Complex.NaN.sinh().isNaN()); } - + public void testSinhInf() { TestUtils.assertSame(Complex.NaN, oneInf.sinh()); TestUtils.assertSame(Complex.NaN, oneNegInf.sinh()); @@ -598,37 +598,37 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, negInfInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sinh()); } - + public void testSqrtRealPositive() { Complex z = new Complex(3, 4); Complex expected = new Complex(2, 1); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } - + public void testSqrtRealZero() { Complex z = new Complex(0.0, 4); Complex expected = new Complex(1.41421, 1.41421); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } - + public void testSqrtRealNegative() { Complex z = new Complex(-3.0, 4); Complex expected = new Complex(1, 2); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } - + public void testSqrtImaginaryZero() { Complex z = new Complex(-3.0, 0.0); Complex expected = new Complex(0.0, 1.73205); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } - + public void testSqrtImaginaryNegative() { Complex z = new Complex(-3.0, -4.0); Complex expected = new Complex(1.0, -2.0); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } - + public void testSqrtPolar() { double r = 1; for (int i = 0; i < 5; i++) { @@ -640,13 +640,13 @@ public class ComplexTest extends TestCase { Complex sqrtz = ComplexUtils.polar2Complex(Math.sqrt(r), theta / 2); TestUtils.assertEquals(sqrtz, z.sqrt(), 10e-12); } - } + } } - + public void testSqrtNaN() { assertTrue(Complex.NaN.sqrt().isNaN()); } - + public void testSqrtInf() { TestUtils.assertSame(infNaN, oneInf.sqrt()); TestUtils.assertSame(infNaN, oneNegInf.sqrt()); @@ -657,27 +657,27 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(nanInf, negInfInf.sqrt()); TestUtils.assertSame(nanNegInf, negInfNegInf.sqrt()); } - + public void testSqrt1z() { Complex z = new Complex(3, 4); Complex expected = new Complex(4.08033, -2.94094); TestUtils.assertEquals(expected, z.sqrt1z(), 1.0e-5); } - + public void testSqrt1zNaN() { assertTrue(Complex.NaN.sqrt1z().isNaN()); } - + public void testTan() { Complex z = new Complex(3, 4); Complex expected = new Complex(-0.000187346, 0.999356); TestUtils.assertEquals(expected, z.tan(), 1.0e-5); } - + public void testTanNaN() { assertTrue(Complex.NaN.tan().isNaN()); } - + public void testTanInf() { TestUtils.assertSame(zeroNaN, oneInf.tan()); TestUtils.assertSame(zeroNaN, oneNegInf.tan()); @@ -688,22 +688,22 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, negInfInf.tan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tan()); } - + public void testTanCritical() { TestUtils.assertSame(infNaN, new Complex(pi/2, 0).tan()); TestUtils.assertSame(negInfNaN, new Complex(-pi/2, 0).tan()); } - + public void testTanh() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.00071, 0.00490826); TestUtils.assertEquals(expected, z.tanh(), 1.0e-5); } - + public void testTanhNaN() { assertTrue(Complex.NaN.tanh().isNaN()); } - + public void testTanhInf() { TestUtils.assertSame(Complex.NaN, oneInf.tanh()); TestUtils.assertSame(Complex.NaN, oneNegInf.tanh()); @@ -714,7 +714,7 @@ public class ComplexTest extends TestCase { TestUtils.assertSame(Complex.NaN, negInfInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tanh()); } - + public void testTanhCritical() { TestUtils.assertSame(nanInf, new Complex(0, pi/2).tanh()); } @@ -723,8 +723,8 @@ public class ComplexTest extends TestCase { public void testMath221() { assertEquals(new Complex(0,-1), new Complex(0,1).multiply(new Complex(-1,0))); } - - /** + + /** * Test: computing third roots of z. *

            * 
      @@ -743,7 +743,7 @@ public class ComplexTest extends TestCase {
               // Returned Collection must not be empty!
               assertEquals(3, thirdRootsOfZ.length);
               // test z_0
      -        assertEquals(1.0,                  thirdRootsOfZ[0].getReal(),      1.0e-5); 
      +        assertEquals(1.0,                  thirdRootsOfZ[0].getReal(),      1.0e-5);
               assertEquals(1.0,                  thirdRootsOfZ[0].getImaginary(), 1.0e-5);
               // test z_1
               assertEquals(-1.3660254037844386,  thirdRootsOfZ[1].getReal(),      1.0e-5);
      @@ -754,7 +754,7 @@ public class ComplexTest extends TestCase {
           }
       
       
      -    /** 
      +    /**
            * Test: computing fourth roots of z.
            * 
            * 
      @@ -774,7 +774,7 @@ public class ComplexTest extends TestCase {
               // Returned Collection must not be empty!
               assertEquals(4, fourthRootsOfZ.length);
               // test z_0
      -        assertEquals(1.5164629308487783,     fourthRootsOfZ[0].getReal(),      1.0e-5); 
      +        assertEquals(1.5164629308487783,     fourthRootsOfZ[0].getReal(),      1.0e-5);
               assertEquals(-0.14469266210702247,   fourthRootsOfZ[0].getImaginary(), 1.0e-5);
               // test z_1
               assertEquals(0.14469266210702256,    fourthRootsOfZ[1].getReal(),      1.0e-5);
      @@ -787,7 +787,7 @@ public class ComplexTest extends TestCase {
               assertEquals(-1.5164629308487783,    fourthRootsOfZ[3].getImaginary(), 1.0e-5);
           }
       
      -    /** 
      +    /**
            * Test: computing third roots of z.
            * 
            * 
      @@ -807,7 +807,7 @@ public class ComplexTest extends TestCase {
               // Returned Collection must not be empty!
               assertEquals(3, thirdRootsOfZ.length);
               // test z_0
      -        assertEquals(2.0,                thirdRootsOfZ[0].getReal(),      1.0e-5); 
      +        assertEquals(2.0,                thirdRootsOfZ[0].getReal(),      1.0e-5);
               assertEquals(0.0,                thirdRootsOfZ[0].getImaginary(), 1.0e-5);
               // test z_1
               assertEquals(-1.0,               thirdRootsOfZ[1].getReal(),      1.0e-5);
      @@ -818,7 +818,7 @@ public class ComplexTest extends TestCase {
           }
       
       
      -    /** 
      +    /**
            * Test: computing third roots of z with real part 0.
            * 
            * 
      @@ -837,7 +837,7 @@ public class ComplexTest extends TestCase {
               // Returned Collection must not be empty!
               assertEquals(3, thirdRootsOfZ.length);
               // test z_0
      -        assertEquals(1.0911236359717216,      thirdRootsOfZ[0].getReal(),      1.0e-5); 
      +        assertEquals(1.0911236359717216,      thirdRootsOfZ[0].getReal(),      1.0e-5);
               assertEquals(0.6299605249474365,      thirdRootsOfZ[0].getImaginary(), 1.0e-5);
               // test z_1
               assertEquals(-1.0911236359717216,     thirdRootsOfZ[1].getReal(),      1.0e-5);
      @@ -855,57 +855,57 @@ public class ComplexTest extends TestCase {
               List roots = oneNaN.nthRoot(3);
               assertEquals(1,roots.size());
               assertEquals(Complex.NaN, roots.get(0));
      -        
      +
               roots = nanZero.nthRoot(3);
               assertEquals(1,roots.size());
               assertEquals(Complex.NaN, roots.get(0));
      -        
      +
               // NaN + infinite -> NaN
               roots = nanInf.nthRoot(3);
               assertEquals(1,roots.size());
               assertEquals(Complex.NaN, roots.get(0));
      -        
      +
               // finite + infinite -> Inf
               roots = oneInf.nthRoot(3);
               assertEquals(1,roots.size());
               assertEquals(Complex.INF, roots.get(0));
      -        
      +
               // infinite + infinite -> Inf
               roots = negInfInf.nthRoot(3);
               assertEquals(1,roots.size());
               assertEquals(Complex.INF, roots.get(0));
           }
      -    
      +
           /**
            * Test standard values
            */
           public void testGetArgument() {
               Complex z = new Complex(1, 0);
               assertEquals(0.0, z.getArgument(), 1.0e-12);
      -        
      +
               z = new Complex(1, 1);
               assertEquals(Math.PI/4, z.getArgument(), 1.0e-12);
      -        
      +
               z = new Complex(0, 1);
               assertEquals(Math.PI/2, z.getArgument(), 1.0e-12);
      -        
      +
               z = new Complex(-1, 1);
               assertEquals(3 * Math.PI/4, z.getArgument(), 1.0e-12);
      -        
      +
               z = new Complex(-1, 0);
               assertEquals(Math.PI, z.getArgument(), 1.0e-12);
      -        
      +
               z = new Complex(-1, -1);
               assertEquals(-3 * Math.PI/4, z.getArgument(), 1.0e-12);
      -        
      +
               z = new Complex(0, -1);
               assertEquals(-Math.PI/2, z.getArgument(), 1.0e-12);
      -        
      +
               z = new Complex(1, -1);
               assertEquals(-Math.PI/4, z.getArgument(), 1.0e-12);
      -        
      +
           }
      -    
      +
           /**
            * Verify atan2-style handling of infinite parts
            */
      @@ -916,19 +916,19 @@ public class ComplexTest extends TestCase {
               assertEquals(Math.PI/2, zeroInf.getArgument(), 1.0e-12);
               assertEquals(0.0, infZero.getArgument(), 1.0e-12);
               assertEquals(Math.PI, negInfOne.getArgument(), 1.0e-12);
      -        assertEquals(-3.0*Math.PI/4, negInfNegInf.getArgument(), 1.0e-12);  
      -        assertEquals(-Math.PI/2, oneNegInf.getArgument(), 1.0e-12);        
      +        assertEquals(-3.0*Math.PI/4, negInfNegInf.getArgument(), 1.0e-12);
      +        assertEquals(-Math.PI/2, oneNegInf.getArgument(), 1.0e-12);
           }
      -    
      +
           /**
            * Verify that either part NaN results in NaN
            */
           public void testGetArgumentNaN() {
               assertEquals(nan, nanZero.getArgument());
               assertEquals(nan, zeroNaN.getArgument());
      -        assertEquals(nan, Complex.NaN.getArgument());  
      +        assertEquals(nan, Complex.NaN.getArgument());
           }
      -    
      +
           public void testSerial() {
               Complex z = new Complex(3.0, 4.0);
               assertEquals(z, TestUtils.serializeAndRecover(z));
      @@ -947,7 +947,7 @@ public class ComplexTest extends TestCase {
               assertEquals(infInf, inftcmplx);
               assertTrue(inftcmplx.isInfinite());
           }
      -    
      +
           /**
            * Class to test extending Complex
            */
      @@ -961,7 +961,7 @@ public class ComplexTest extends TestCase {
               public TestComplex(double real, double imaginary) {
                   super(real, imaginary);
               }
      -        
      +
               public TestComplex(Complex other){
                   this(other.getReal(), other.getImaginary());
               }
      diff --git a/src/test/java/org/apache/commons/math/complex/ComplexUtilsTest.java b/src/test/java/org/apache/commons/math/complex/ComplexUtilsTest.java
      index fd88da6df..683fabda8 100644
      --- a/src/test/java/org/apache/commons/math/complex/ComplexUtilsTest.java
      +++ b/src/test/java/org/apache/commons/math/complex/ComplexUtilsTest.java
      @@ -5,9 +5,9 @@
        * The ASF licenses this file to You under the Apache License, Version 2.0
        * (the "License"); you may not use this file except in compliance with
        * the License.  You may obtain a copy of the License at
      - * 
      + *
        *      http://www.apache.org/licenses/LICENSE-2.0
      - * 
      + *
        * Unless required by applicable law or agreed to in writing, software
        * distributed under the License is distributed on an "AS IS" BASIS,
        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      @@ -25,12 +25,12 @@ import junit.framework.TestCase;
        * @version $Revision$ $Date$
        */
       public class ComplexUtilsTest extends TestCase {
      -    
      +
           private double inf = Double.POSITIVE_INFINITY;
           private double negInf = Double.NEGATIVE_INFINITY;
           private double nan = Double.NaN;
           private double pi = Math.PI;
      -    
      +
           private Complex negInfInf = new Complex(negInf, inf);
           private Complex infNegInf = new Complex(inf, negInf);
           private Complex infInf = new Complex(inf, inf);
      @@ -38,15 +38,15 @@ public class ComplexUtilsTest extends TestCase {
           private Complex infNaN = new Complex(inf, nan);
       
           public void testPolar2Complex() {
      -        TestUtils.assertEquals(Complex.ONE, 
      +        TestUtils.assertEquals(Complex.ONE,
                       ComplexUtils.polar2Complex(1, 0), 10e-12);
      -        TestUtils.assertEquals(Complex.ZERO, 
      +        TestUtils.assertEquals(Complex.ZERO,
                       ComplexUtils.polar2Complex(0, 1), 10e-12);
      -        TestUtils.assertEquals(Complex.ZERO, 
      +        TestUtils.assertEquals(Complex.ZERO,
                       ComplexUtils.polar2Complex(0, -1), 10e-12);
      -        TestUtils.assertEquals(Complex.I, 
      +        TestUtils.assertEquals(Complex.I,
                       ComplexUtils.polar2Complex(1, pi/2), 10e-12);
      -        TestUtils.assertEquals(Complex.I.negate(), 
      +        TestUtils.assertEquals(Complex.I.negate(),
                       ComplexUtils.polar2Complex(1, -pi/2), 10e-12);
               double r = 0;
               for (int i = 0; i < 5; i++) {
      @@ -54,38 +54,38 @@ public class ComplexUtilsTest extends TestCase {
                 double theta = 0;
                 for (int j =0; j < 20; j++) {
                     theta += pi / 6;
      -              TestUtils.assertEquals(altPolar(r, theta), 
      +              TestUtils.assertEquals(altPolar(r, theta),
                             ComplexUtils.polar2Complex(r, theta), 10e-12);
                 }
                 theta = -2 * pi;
                 for (int j =0; j < 20; j++) {
                     theta -= pi / 6;
      -              TestUtils.assertEquals(altPolar(r, theta), 
      +              TestUtils.assertEquals(altPolar(r, theta),
                             ComplexUtils.polar2Complex(r, theta), 10e-12);
                 }
      -        }   
      +        }
           }
       
           protected Complex altPolar(double r, double theta) {
               return Complex.I.multiply(new Complex(theta, 0)).exp().multiply(new Complex(r, 0));
           }
      -    
      +
           public void testPolar2ComplexIllegalModulus() {
               try {
                   ComplexUtils.polar2Complex(-1, 0);
                   fail("Expecting IllegalArgumentException");
               } catch (IllegalArgumentException ex) {
                   // expected
      -        }       
      +        }
           }
      -    
      +
           public void testPolar2ComplexNaN() {
               TestUtils.assertSame(Complex.NaN, ComplexUtils.polar2Complex(nan, 1));
               TestUtils.assertSame(Complex.NaN, ComplexUtils.polar2Complex(1, nan));
      -        TestUtils.assertSame(Complex.NaN, 
      -                ComplexUtils.polar2Complex(nan, nan));     
      +        TestUtils.assertSame(Complex.NaN,
      +                ComplexUtils.polar2Complex(nan, nan));
           }
      -    
      +
           public void testPolar2ComplexInf() {
               TestUtils.assertSame(Complex.NaN, ComplexUtils.polar2Complex(1, inf));
               TestUtils.assertSame(Complex.NaN,
      diff --git a/src/test/java/org/apache/commons/math/complex/FrenchComplexFormatTest.java b/src/test/java/org/apache/commons/math/complex/FrenchComplexFormatTest.java
      index 322a2cdd4..9fff723b4 100644
      --- a/src/test/java/org/apache/commons/math/complex/FrenchComplexFormatTest.java
      +++ b/src/test/java/org/apache/commons/math/complex/FrenchComplexFormatTest.java
      @@ -5,9 +5,9 @@
        * The ASF licenses this file to You under the Apache License, Version 2.0
        * (the "License"); you may not use this file except in compliance with
        * the License.  You may obtain a copy of the License at
      - * 
      + *
        *      http://www.apache.org/licenses/LICENSE-2.0
      - * 
      + *
        * Unless required by applicable law or agreed to in writing, software
        * distributed under the License is distributed on an "AS IS" BASIS,
        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      diff --git a/src/test/java/org/apache/commons/math/distribution/BinomialDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/BinomialDistributionTest.java
      index c05b43101..0f577d3c9 100644
      --- a/src/test/java/org/apache/commons/math/distribution/BinomialDistributionTest.java
      +++ b/src/test/java/org/apache/commons/math/distribution/BinomialDistributionTest.java
      @@ -5,9 +5,9 @@
        * The ASF licenses this file to You under the Apache License, Version 2.0
        * (the "License"); you may not use this file except in compliance with
        * the License.  You may obtain a copy of the License at
      - * 
      + *
        *      http://www.apache.org/licenses/LICENSE-2.0
      - * 
      + *
        * Unless required by applicable law or agreed to in writing, software
        * distributed under the License is distributed on an "AS IS" BASIS,
        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      @@ -20,11 +20,11 @@ package org.apache.commons.math.distribution;
        * Test cases for BinomialDistribution.
        * Extends IntegerDistributionAbstractTest.  See class javadoc for
        * IntegerDistributionAbstractTest for details.
      - * 
      + *
        * @version $Revision$ $Date$
        */
       public class BinomialDistributionTest extends IntegerDistributionAbstractTest {
      -    
      +
           /**
            * Constructor for BinomialDistributionTest.
            * @param name
      @@ -32,48 +32,48 @@ public class BinomialDistributionTest extends IntegerDistributionAbstractTest {
           public BinomialDistributionTest(String name) {
               super(name);
           }
      -    
      +
           //-------------- Implementations for abstract methods -----------------------
      -    
      +
           /** Creates the default discrete distribution instance to use in tests. */
           @Override
           public IntegerDistribution makeDistribution() {
               return new BinomialDistributionImpl(10,0.70);
           }
      -    
      +
           /** Creates the default probability density test input values */
           @Override
           public int[] makeDensityTestPoints() {
               return new int[] {-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
           }
      -    
      +
           /** Creates the default probability density test expected values */
           @Override
           public double[] makeDensityTestValues() {
      -        return new double[] {0d, 0.0000d, 0.0001d, 0.0014d, 0.0090d, 0.0368d, 0.1029d, 
      +        return new double[] {0d, 0.0000d, 0.0001d, 0.0014d, 0.0090d, 0.0368d, 0.1029d,
                       0.2001d, 0.2668d, 0.2335d, 0.1211d, 0.0282d, 0d};
           }
      -    
      +
           /** Creates the default cumulative probability density test input values */
           @Override
           public int[] makeCumulativeTestPoints() {
               return makeDensityTestPoints();
           }
      -    
      +
           /** Creates the default cumulative probability density test expected values */
           @Override
           public double[] makeCumulativeTestValues() {
               return new double[] {0d, 0.0000d, 0.0001d, 0.0016d, 0.0106d, 0.0473d,
                       0.1503d, 0.3504d, 0.6172d, 0.8507d, 0.9718d, 1d, 1d};
               }
      -    
      +
           /** Creates the default inverse cumulative probability test input values */
           @Override
           public double[] makeInverseCumulativeTestPoints() {
               return new double[] {0, 0.001d, 0.010d, 0.025d, 0.050d, 0.100d, 0.999d,
      -                0.990d, 0.975d, 0.950d, 0.900d,1}; 
      +                0.990d, 0.975d, 0.950d, 0.900d,1};
               }
      -    
      +
           /** Creates the default inverse cumulative probability density test expected values */
           @Override
           public int[] makeInverseCumulativeTestValues() {
      @@ -81,7 +81,7 @@ public class BinomialDistributionTest extends IntegerDistributionAbstractTest {
           }
       
           //----------------- Additional test cases ---------------------------------
      -   
      +
           /** Test degenerate case p = 0   */
           public void testDegenerate0() throws Exception {
               setDistribution(new BinomialDistributionImpl(5,0.0d));
      @@ -93,9 +93,9 @@ public class BinomialDistributionTest extends IntegerDistributionAbstractTest {
               setInverseCumulativeTestValues(new int[] {-1, -1});
               verifyDensities();
               verifyCumulativeProbabilities();
      -        verifyInverseCumulativeProbabilities();     
      +        verifyInverseCumulativeProbabilities();
           }
      -    
      +
           /** Test degenerate case p = 1   */
           public void testDegenerate1() throws Exception {
               setDistribution(new BinomialDistributionImpl(5,1.0d));
      @@ -107,7 +107,7 @@ public class BinomialDistributionTest extends IntegerDistributionAbstractTest {
               setInverseCumulativeTestValues(new int[] {4, 4});
               verifyDensities();
               verifyCumulativeProbabilities();
      -        verifyInverseCumulativeProbabilities();     
      +        verifyInverseCumulativeProbabilities();
           }
       
       }
      diff --git a/src/test/java/org/apache/commons/math/distribution/CauchyDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/CauchyDistributionTest.java
      index 6e29b395f..94de0a827 100644
      --- a/src/test/java/org/apache/commons/math/distribution/CauchyDistributionTest.java
      +++ b/src/test/java/org/apache/commons/math/distribution/CauchyDistributionTest.java
      @@ -21,11 +21,11 @@ package org.apache.commons.math.distribution;
        * Test cases for CauchyDistribution.
        * Extends ContinuousDistributionAbstractTest.  See class javadoc for
        * ContinuousDistributionAbstractTest for details.
      - * 
      + *
        * @version $Revision$ $Date$
        */
       public class CauchyDistributionTest extends ContinuousDistributionAbstractTest  {
      -    
      +
           /**
            * Constructor for CauchyDistributionTest.
            * @param arg0
      @@ -33,54 +33,54 @@ public class CauchyDistributionTest extends ContinuousDistributionAbstractTest
           public CauchyDistributionTest(String arg0) {
               super(arg0);
           }
      -    
      +
           //-------------- Implementations for abstract methods -----------------------
      -    
      +
           /** Creates the default continuous distribution instance to use in tests. */
           @Override
           public ContinuousDistribution makeDistribution() {
               return new CauchyDistributionImpl(1.2, 2.1);
      -    }   
      -    
      +    }
      +
           /** Creates the default cumulative probability distribution test input values */
           @Override
           public double[] makeCumulativeTestPoints() {
      -        // quantiles computed using Mathematica 
      +        // quantiles computed using Mathematica
               return new double[] {-667.2485619d, -65.6230835d, -25.48302995d,
                       -12.05887818d, -5.263135428d, 7.663135428d, 14.45887818d,
                       27.88302995d, 68.0230835d, 669.6485619d};
           }
      -    
      +
           /** Creates the default cumulative probability density test expected values */
           @Override
           public double[] makeCumulativeTestValues() {
               return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.900d, 0.950d,
                       0.975d, 0.990d, 0.999d};
           }
      -    
      +
           //---------------------------- Additional test cases -------------------------
      -    
      +
           public void testInverseCumulativeProbabilityExtremes() throws Exception {
               setInverseCumulativeTestPoints(new double[] {0.0, 1.0});
               setInverseCumulativeTestValues(
                       new double[] {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY});
               verifyInverseCumulativeProbabilities();
           }
      -    
      +
           public void testMedian() {
               CauchyDistribution distribution = (CauchyDistribution) getDistribution();
               double expected = Math.random();
               distribution.setMedian(expected);
               assertEquals(expected, distribution.getMedian(), 0.0);
           }
      -    
      +
           public void testScale() {
               CauchyDistribution distribution = (CauchyDistribution) getDistribution();
               double expected = Math.random();
               distribution.setScale(expected);
               assertEquals(expected, distribution.getScale(), 0.0);
           }
      -    
      +
           public void testSetScale() {
               CauchyDistribution distribution = (CauchyDistribution) getDistribution();
               try {
      @@ -89,7 +89,7 @@ public class CauchyDistributionTest extends ContinuousDistributionAbstractTest
               } catch (IllegalArgumentException ex) {
                   // success
               }
      -        
      +
               try {
                   distribution.setScale(-1.0);
                   fail("Can not have negative scale.");
      diff --git a/src/test/java/org/apache/commons/math/distribution/ChiSquareDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/ChiSquareDistributionTest.java
      index aa14f8b78..b09f6272d 100644
      --- a/src/test/java/org/apache/commons/math/distribution/ChiSquareDistributionTest.java
      +++ b/src/test/java/org/apache/commons/math/distribution/ChiSquareDistributionTest.java
      @@ -5,9 +5,9 @@
        * The ASF licenses this file to You under the Apache License, Version 2.0
        * (the "License"); you may not use this file except in compliance with
        * the License.  You may obtain a copy of the License at
      - * 
      + *
        *      http://www.apache.org/licenses/LICENSE-2.0
      - * 
      + *
        * Unless required by applicable law or agreed to in writing, software
        * distributed under the License is distributed on an "AS IS" BASIS,
        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      @@ -21,11 +21,11 @@ package org.apache.commons.math.distribution;
        * Test cases for ChiSquareDistribution.
        * Extends ContinuousDistributionAbstractTest.  See class javadoc for
        * ContinuousDistributionAbstractTest for details.
      - * 
      + *
        * @version $Revision$ $Date$
        */
       public class ChiSquareDistributionTest extends ContinuousDistributionAbstractTest {
      -    
      +
           /**
            * Constructor for ChiSquareDistributionTest.
            * @param name
      @@ -33,45 +33,45 @@ public class ChiSquareDistributionTest extends ContinuousDistributionAbstractTes
           public ChiSquareDistributionTest(String name) {
               super(name);
           }
      -    
      +
           //-------------- Implementations for abstract methods -----------------------
      -    
      +
           /** Creates the default continuous distribution instance to use in tests. */
           @Override
           public ContinuousDistribution makeDistribution() {
               return new ChiSquaredDistributionImpl(5.0);
      -    }   
      -    
      +    }
      +
           /** Creates the default cumulative probability distribution test input values */
           @Override
           public double[] makeCumulativeTestPoints() {
               // quantiles computed using R version 1.8.1 (linux version)
      -        return new double[] {0.210216d, 0.5542981d, 0.8312116d, 1.145476d, 1.610308d, 
      +        return new double[] {0.210216d, 0.5542981d, 0.8312116d, 1.145476d, 1.610308d,
                       20.51501d, 15.08627d, 12.83250d, 11.07050d, 9.236357d};
           }
      -    
      +
           /** Creates the default cumulative probability density test expected values */
           @Override
           public double[] makeCumulativeTestValues() {
               return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d,
      -                0.990d, 0.975d, 0.950d, 0.900d}; 
      +                0.990d, 0.975d, 0.950d, 0.900d};
           }
      -    
      +
           /** Creates the default inverse cumulative probability test input values */
           @Override
           public double[] makeInverseCumulativeTestPoints() {
               return new double[] {0, 0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d,
      -                0.990d, 0.975d, 0.950d, 0.900d, 1};     
      +                0.990d, 0.975d, 0.950d, 0.900d, 1};
           }
      -    
      +
           /** Creates the default inverse cumulative probability density test expected values */
           @Override
           public double[] makeInverseCumulativeTestValues() {
      -        return new double[] {0, 0.210216d, 0.5542981d, 0.8312116d, 1.145476d, 1.610308d, 
      -                20.51501d, 15.08627d, 12.83250d, 11.07050d, 9.236357d, 
      +        return new double[] {0, 0.210216d, 0.5542981d, 0.8312116d, 1.145476d, 1.610308d,
      +                20.51501d, 15.08627d, 12.83250d, 11.07050d, 9.236357d,
                       Double.POSITIVE_INFINITY};
           }
      -    
      +
        // --------------------- Override tolerance  --------------
           @Override
           protected void setUp() throws Exception {
      @@ -80,20 +80,20 @@ public class ChiSquareDistributionTest extends ContinuousDistributionAbstractTes
           }
       
        //---------------------------- Additional test cases -------------------------
      -    
      +
           public void testSmallDf() throws Exception {
               setDistribution(new ChiSquaredDistributionImpl(0.1d));
               setTolerance(1E-4);
               // quantiles computed using R version 1.8.1 (linux version)
      -        setCumulativeTestPoints(new double[] {1.168926E-60, 1.168926E-40, 1.063132E-32, 
      -                1.144775E-26, 1.168926E-20, 5.472917, 2.175255, 1.13438, 
      +        setCumulativeTestPoints(new double[] {1.168926E-60, 1.168926E-40, 1.063132E-32,
      +                1.144775E-26, 1.168926E-20, 5.472917, 2.175255, 1.13438,
                       0.5318646, 0.1526342});
               setInverseCumulativeTestValues(getCumulativeTestPoints());
               setInverseCumulativeTestPoints(getCumulativeTestValues());
               verifyCumulativeProbabilities();
               verifyInverseCumulativeProbabilities();
           }
      -    
      +
           public void testDfAccessors() {
               ChiSquaredDistribution distribution = (ChiSquaredDistribution) getDistribution();
               assertEquals(5d, distribution.getDegreesOfFreedom(), Double.MIN_VALUE);
      diff --git a/src/test/java/org/apache/commons/math/distribution/ContinuousDistributionAbstractTest.java b/src/test/java/org/apache/commons/math/distribution/ContinuousDistributionAbstractTest.java
      index a7861db73..ab7f32d0f 100644
      --- a/src/test/java/org/apache/commons/math/distribution/ContinuousDistributionAbstractTest.java
      +++ b/src/test/java/org/apache/commons/math/distribution/ContinuousDistributionAbstractTest.java
      @@ -5,9 +5,9 @@
        * The ASF licenses this file to You under the Apache License, Version 2.0
        * (the "License"); you may not use this file except in compliance with
        * the License.  You may obtain a copy of the License at
      - * 
      + *
        *      http://www.apache.org/licenses/LICENSE-2.0
      - * 
      + *
        * Unless required by applicable law or agreed to in writing, software
        * distributed under the License is distributed on an "AS IS" BASIS,
        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      @@ -39,7 +39,7 @@ import org.apache.commons.math.TestUtils;
        * 

      * To implement additional test cases with different distribution instances and * test data, use the setXxx methods for the instance data in test cases and - * call the verifyXxx methods to verify results. + * call the verifyXxx methods to verify results. *

      * Error tolerance can be overriden by implementing getTolerance(). *

      @@ -50,32 +50,32 @@ import org.apache.commons.math.TestUtils; *

      * See {@link NormalDistributionTest} and {@link ChiSquareDistributionTest} * for examples. - * + * * @version $Revision$ $Date$ */ public abstract class ContinuousDistributionAbstractTest extends TestCase { - + //-------------------- Private test instance data ------------------------- /** Distribution instance used to perform tests */ private ContinuousDistribution distribution; - + /** Tolerance used in comparing expected and returned values */ private double tolerance = 1E-4; - + /** Arguments used to test cumulative probability density calculations */ private double[] cumulativeTestPoints; - + /** Values used to test cumulative probability density calculations */ private double[] cumulativeTestValues; - + /** Arguments used to test inverse cumulative probability density calculations */ private double[] inverseCumulativeTestPoints; - + /** Values used to test inverse cumulative probability density calculations */ private double[] inverseCumulativeTestValues; - + //------------------------------------------------------------------------- - + /** * Constructor for ContinuousDistributionAbstractTest. * @param name @@ -83,34 +83,34 @@ public abstract class ContinuousDistributionAbstractTest extends TestCase { public ContinuousDistributionAbstractTest(String name) { super(name); } - + //-------------------- Abstract methods ----------------------------------- - + /** Creates the default continuous distribution instance to use in tests. */ public abstract ContinuousDistribution makeDistribution(); - + /** Creates the default cumulative probability density test input values */ public abstract double[] makeCumulativeTestPoints(); - + /** Creates the default cumulative probability density test expected values */ public abstract double[] makeCumulativeTestValues(); - + //---- Default implementations of inverse test data generation methods ---- - + /** Creates the default inverse cumulative probability test input values */ public double[] makeInverseCumulativeTestPoints() { return makeCumulativeTestValues(); } - + /** Creates the default inverse cumulative probability density test expected values */ public double[] makeInverseCumulativeTestValues() { return makeCumulativeTestPoints(); } - + //-------------------- Setup / tear down ---------------------------------- - + /** - * Setup sets all test instance data to default values + * Setup sets all test instance data to default values */ @Override protected void setUp() throws Exception { @@ -119,90 +119,90 @@ public abstract class ContinuousDistributionAbstractTest extends TestCase { cumulativeTestPoints = makeCumulativeTestPoints(); cumulativeTestValues = makeCumulativeTestValues(); inverseCumulativeTestPoints = makeInverseCumulativeTestPoints(); - inverseCumulativeTestValues = makeInverseCumulativeTestValues(); + inverseCumulativeTestValues = makeInverseCumulativeTestValues(); } - + /** * Cleans up test instance data */ @Override - protected void tearDown() throws Exception { + protected void tearDown() throws Exception { super.tearDown(); distribution = null; cumulativeTestPoints = null; cumulativeTestValues = null; inverseCumulativeTestPoints = null; - inverseCumulativeTestValues = null; + inverseCumulativeTestValues = null; } - + //-------------------- Verification methods ------------------------------- - + /** * Verifies that cumulative probability density calculations match expected values * using current test instance data - */ + */ protected void verifyCumulativeProbabilities() throws Exception { for (int i = 0; i < cumulativeTestPoints.length; i++) { - TestUtils.assertEquals("Incorrect cumulative probability value returned for " - + cumulativeTestPoints[i], cumulativeTestValues[i], - distribution.cumulativeProbability(cumulativeTestPoints[i]), + TestUtils.assertEquals("Incorrect cumulative probability value returned for " + + cumulativeTestPoints[i], cumulativeTestValues[i], + distribution.cumulativeProbability(cumulativeTestPoints[i]), getTolerance()); - } + } } - + /** * Verifies that inverse cumulative probability density calculations match expected values * using current test instance data */ protected void verifyInverseCumulativeProbabilities() throws Exception { for (int i = 0; i < inverseCumulativeTestPoints.length; i++) { - TestUtils.assertEquals("Incorrect inverse cumulative probability value returned for " - + inverseCumulativeTestPoints[i], inverseCumulativeTestValues[i], - distribution.inverseCumulativeProbability(inverseCumulativeTestPoints[i]), + TestUtils.assertEquals("Incorrect inverse cumulative probability value returned for " + + inverseCumulativeTestPoints[i], inverseCumulativeTestValues[i], + distribution.inverseCumulativeProbability(inverseCumulativeTestPoints[i]), getTolerance()); - } + } } - + //------------------------ Default test cases ----------------------------- - + /** * Verifies that cumulative probability density calculations match expected values * using default test instance data */ public void testCumulativeProbabilities() throws Exception { - verifyCumulativeProbabilities(); + verifyCumulativeProbabilities(); } - + /** * Verifies that inverse cumulative probability density calculations match expected values * using default test instance data */ public void testInverseCumulativeProbabilities() throws Exception { - verifyInverseCumulativeProbabilities(); + verifyInverseCumulativeProbabilities(); } - + /** * Verifies that probability computations are consistent */ public void testConsistency() throws Exception { for (int i=1; i < cumulativeTestPoints.length; i++) { - + // check that cdf(x, x) = 0 - TestUtils.assertEquals(0d, + TestUtils.assertEquals(0d, distribution.cumulativeProbability (cumulativeTestPoints[i], cumulativeTestPoints[i]), tolerance); - + // check that P(a < X < b) = P(X < b) - P(X < a) double upper = Math.max(cumulativeTestPoints[i], cumulativeTestPoints[i -1]); double lower = Math.min(cumulativeTestPoints[i], cumulativeTestPoints[i -1]); - double diff = distribution.cumulativeProbability(upper) - + double diff = distribution.cumulativeProbability(upper) - distribution.cumulativeProbability(lower); double direct = distribution.cumulativeProbability(lower, upper); - TestUtils.assertEquals("Inconsistent cumulative probabilities for (" + TestUtils.assertEquals("Inconsistent cumulative probabilities for (" + lower + "," + upper + ")", diff, direct, tolerance); } } - + /** * Verifies that illegal arguments are correctly handled */ @@ -224,9 +224,9 @@ public abstract class ContinuousDistributionAbstractTest extends TestCase { fail("Expecting IllegalArgumentException for p = 2"); } catch (IllegalArgumentException ex) { // expected - } + } } - + //------------------ Getters / Setters for test instance data ----------- /** * @return Returns the cumulativeTestPoints. diff --git a/src/test/java/org/apache/commons/math/distribution/ExponentialDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/ExponentialDistributionTest.java index 4d5446060..6c8abfea8 100644 --- a/src/test/java/org/apache/commons/math/distribution/ExponentialDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/ExponentialDistributionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +20,7 @@ package org.apache.commons.math.distribution; * Test cases for ExponentialDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. - * + * * @version $Revision$ $Date$ */ public class ExponentialDistributionTest extends ContinuousDistributionAbstractTest { @@ -34,30 +34,30 @@ public class ExponentialDistributionTest extends ContinuousDistributionAbstractT } //-------------- Implementations for abstract methods ----------------------- - + /** Creates the default continuous distribution instance to use in tests. */ @Override public ContinuousDistribution makeDistribution() { return new ExponentialDistributionImpl(5.0); - } - + } + /** Creates the default cumulative probability distribution test input values */ @Override public double[] makeCumulativeTestPoints() { // quantiles computed using R version 1.8.1 (linux version) - return new double[] {0.005002502d, 0.05025168d, 0.1265890d, 0.2564665d, 0.5268026d, + return new double[] {0.005002502d, 0.05025168d, 0.1265890d, 0.2564665d, 0.5268026d, 34.53878d, 23.02585d, 18.44440d, 14.97866d, 11.51293d}; } - + /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d, - 0.990d, 0.975d, 0.950d, 0.900d}; + 0.990d, 0.975d, 0.950d, 0.900d}; } - + //------------ Additional tests ------------------------------------------- - + public void testCumulativeProbabilityExtremes() throws Exception { setCumulativeTestPoints(new double[] {-2, 0}); setCumulativeTestValues(new double[] {0, 0}); @@ -91,7 +91,7 @@ public class ExponentialDistributionTest extends ContinuousDistributionAbstractT // computed using print(dexp(2, rate=1/3), digits=10) in R 2.5 assertEquals(0.1711390397, d2.density(2.0), 1e-8); } - + public void testMeanAccessors() { ExponentialDistribution distribution = (ExponentialDistribution) getDistribution(); assertEquals(5d, distribution.getMean(), Double.MIN_VALUE); @@ -104,5 +104,5 @@ public class ExponentialDistributionTest extends ContinuousDistributionAbstractT // expected } } - + } diff --git a/src/test/java/org/apache/commons/math/distribution/FDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/FDistributionTest.java index a773b1262..661b34051 100644 --- a/src/test/java/org/apache/commons/math/distribution/FDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/FDistributionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +21,7 @@ package org.apache.commons.math.distribution; * Test cases for FDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. - * + * * @version $Revision$ $Date$ */ public class FDistributionTest extends ContinuousDistributionAbstractTest { @@ -35,29 +35,29 @@ public class FDistributionTest extends ContinuousDistributionAbstractTest { } //-------------- Implementations for abstract methods ----------------------- - + /** Creates the default continuous distribution instance to use in tests. */ @Override public ContinuousDistribution makeDistribution() { return new FDistributionImpl(5.0, 6.0); - } - + } + /** Creates the default cumulative probability distribution test input values */ @Override public double[] makeCumulativeTestPoints() { // quantiles computed using R version 1.8.1 (linux version) return new double[] {0.03468084d ,0.09370091d, 0.1433137d, - 0.2020084d, 0.2937283d, 20.80266d, 8.745895d, 5.987565d, + 0.2020084d, 0.2937283d, 20.80266d, 8.745895d, 5.987565d, 4.387374d, 3.107512d}; } - + /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d, - 0.990d, 0.975d, 0.950d, 0.900d}; + 0.990d, 0.975d, 0.950d, 0.900d}; } - + // --------------------- Override tolerance -------------- @Override protected void setUp() throws Exception { @@ -78,7 +78,7 @@ public class FDistributionTest extends ContinuousDistributionAbstractTest { setInverseCumulativeTestValues(new double[] {0, Double.POSITIVE_INFINITY}); verifyInverseCumulativeProbabilities(); } - + public void testDfAccessors() { FDistribution distribution = (FDistribution) getDistribution(); assertEquals(5d, distribution.getNumeratorDegreesOfFreedom(), Double.MIN_VALUE); @@ -99,7 +99,7 @@ public class FDistributionTest extends ContinuousDistributionAbstractTest { } catch (IllegalArgumentException ex) { // expected } - } + } public void testLargeDegreesOfFreedom() throws Exception { org.apache.commons.math.distribution.FDistributionImpl fd = diff --git a/src/test/java/org/apache/commons/math/distribution/GammaDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/GammaDistributionTest.java index 2bf82defc..6f98da122 100644 --- a/src/test/java/org/apache/commons/math/distribution/GammaDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/GammaDistributionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,11 +21,11 @@ package org.apache.commons.math.distribution; * Test cases for GammaDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. - * + * * @version $Revision$ $Date$ */ public class GammaDistributionTest extends ContinuousDistributionAbstractTest { - + /** * Constructor for GammaDistributionTest. * @param name diff --git a/src/test/java/org/apache/commons/math/distribution/HypergeometricDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/HypergeometricDistributionTest.java index 7ebef9cd9..24b2f8765 100644 --- a/src/test/java/org/apache/commons/math/distribution/HypergeometricDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/HypergeometricDistributionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,7 +23,7 @@ import org.apache.commons.math.TestUtils; * Test cases for HyperGeometriclDistribution. * Extends IntegerDistributionAbstractTest. See class javadoc for * IntegerDistributionAbstractTest for details. - * + * * @version $Revision$ $Date$ */ public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest { @@ -37,54 +37,54 @@ public class HypergeometricDistributionTest extends IntegerDistributionAbstractT } //-------------- Implementations for abstract methods ----------------------- - + /** Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { return new HypergeometricDistributionImpl(10,5, 5); } - + /** Creates the default probability density test input values */ @Override public int[] makeDensityTestPoints() { return new int[] {-1, 0, 1, 2, 3, 4, 5, 10}; } - + /** Creates the default probability density test expected values */ @Override public double[] makeDensityTestValues() { - return new double[] {0d, 0.003968d, 0.099206d, 0.396825d, 0.396825d, + return new double[] {0d, 0.003968d, 0.099206d, 0.396825d, 0.396825d, 0.099206d, 0.003968d, 0d}; } - + /** Creates the default cumulative probability density test input values */ @Override public int[] makeCumulativeTestPoints() { return makeDensityTestPoints(); } - + /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0d, .003968d, .103175d, .50000d, .896825d, .996032d, 1.00000d, 1d}; } - + /** Creates the default inverse cumulative probability test input values */ @Override public double[] makeInverseCumulativeTestPoints() { return new double[] {0d, 0.001d, 0.010d, 0.025d, 0.050d, 0.100d, 0.999d, - 0.990d, 0.975d, 0.950d, 0.900d, 1d}; + 0.990d, 0.975d, 0.950d, 0.900d, 1d}; } - + /** Creates the default inverse cumulative probability density test expected values */ @Override public int[] makeInverseCumulativeTestValues() { return new int[] {-1, -1, 0, 0, 0, 0, 4, 3, 3, 3, 3, 5}; } - + //-------------------- Additional test cases ------------------------------ - + /** Verify that if there are no failures, mass is concentrated on sampleSize */ public void testDegenerateNoFailures() throws Exception { setDistribution(new HypergeometricDistributionImpl(5,5,3)); @@ -96,9 +96,9 @@ public class HypergeometricDistributionTest extends IntegerDistributionAbstractT setInverseCumulativeTestValues(new int[] {2, 2}); verifyDensities(); verifyCumulativeProbabilities(); - verifyInverseCumulativeProbabilities(); + verifyInverseCumulativeProbabilities(); } - + /** Verify that if there are no successes, mass is concentrated on 0 */ public void testDegenerateNoSuccesses() throws Exception { setDistribution(new HypergeometricDistributionImpl(5,0,3)); @@ -110,9 +110,9 @@ public class HypergeometricDistributionTest extends IntegerDistributionAbstractT setInverseCumulativeTestValues(new int[] {-1, -1}); verifyDensities(); verifyCumulativeProbabilities(); - verifyInverseCumulativeProbabilities(); + verifyInverseCumulativeProbabilities(); } - + /** Verify that if sampleSize = populationSize, mass is concentrated on numberOfSuccesses */ public void testDegenerateFullSample() throws Exception { setDistribution(new HypergeometricDistributionImpl(5,3,5)); @@ -124,7 +124,7 @@ public class HypergeometricDistributionTest extends IntegerDistributionAbstractT setInverseCumulativeTestValues(new int[] {2, 2}); verifyDensities(); verifyCumulativeProbabilities(); - verifyInverseCumulativeProbabilities(); + verifyInverseCumulativeProbabilities(); } public void testPopulationSize() { @@ -134,11 +134,11 @@ public class HypergeometricDistributionTest extends IntegerDistributionAbstractT fail("negative population size. IllegalArgumentException expected"); } catch(IllegalArgumentException ex) { } - + dist.setPopulationSize(10); assertEquals(10, dist.getPopulationSize()); } - + public void testLargeValues() { int populationSize = 3456; int sampleSize = 789; @@ -150,20 +150,20 @@ public class HypergeometricDistributionTest extends IntegerDistributionAbstractT {3.0, 1.32724172984193e-8, 1.46736255879763e-8, 0.999999998598792}, {4.0, 9.94501711734089e-8, 1.14123796761385e-7, 0.999999985326375}, {5.0, 5.89080768883643e-7, 7.03204565645028e-7, 0.999999885876203}, - {20.0, 0.0760051397707708, 0.27349758476299, 0.802507555007781}, - {21.0, 0.087144222047629, 0.360641806810619, 0.72650241523701}, - {22.0, 0.0940378846881819, 0.454679691498801, 0.639358193189381}, - {23.0, 0.0956897500614809, 0.550369441560282, 0.545320308501199}, - {24.0, 0.0919766921922999, 0.642346133752582, 0.449630558439718}, - {25.0, 0.083641637261095, 0.725987771013677, 0.357653866247418}, + {20.0, 0.0760051397707708, 0.27349758476299, 0.802507555007781}, + {21.0, 0.087144222047629, 0.360641806810619, 0.72650241523701}, + {22.0, 0.0940378846881819, 0.454679691498801, 0.639358193189381}, + {23.0, 0.0956897500614809, 0.550369441560282, 0.545320308501199}, + {24.0, 0.0919766921922999, 0.642346133752582, 0.449630558439718}, + {25.0, 0.083641637261095, 0.725987771013677, 0.357653866247418}, {96.0, 5.93849188852098e-57, 1.0, 6.01900244560712e-57}, - {97.0, 7.96593036832547e-59, 1.0, 8.05105570861321e-59}, + {97.0, 7.96593036832547e-59, 1.0, 8.05105570861321e-59}, {98.0, 8.44582921934367e-61, 1.0, 8.5125340287733e-61}, - {99.0, 6.63604297068222e-63, 1.0, 6.670480942963e-63}, + {99.0, 6.63604297068222e-63, 1.0, 6.670480942963e-63}, {100.0, 3.43501099007557e-65, 1.0, 3.4437972280786e-65}, {101.0, 8.78623800302957e-68, 1.0, 8.78623800302957e-68}, }; - + testHypergeometricDistributionProbabilities(populationSize, sampleSize, numberOfSucceses, data); } @@ -184,30 +184,30 @@ public class HypergeometricDistributionTest extends IntegerDistributionAbstractT TestUtils.assertRelativelyEquals(cdf1, actualCdf1, 1.0e-9); } } - + public void testMoreLargeValues() { int populationSize = 26896; int sampleSize = 895; int numberOfSucceses = 55; double[][] data = { - {0.0, 0.155168304750504, 0.155168304750504, 1.0}, - {1.0, 0.29437545000746, 0.449543754757964, 0.844831695249496}, - {2.0, 0.273841321577003, 0.723385076334967, 0.550456245242036}, - {3.0, 0.166488572570786, 0.889873648905753, 0.276614923665033}, - {4.0, 0.0743969744713231, 0.964270623377076, 0.110126351094247}, - {5.0, 0.0260542785784855, 0.990324901955562, 0.0357293766229237}, - {20.0, 3.57101101678792e-16, 1.0, 3.78252101622096e-16}, - {21.0, 2.00551638598312e-17, 1.0, 2.11509999433041e-17}, - {22.0, 1.04317070180562e-18, 1.0, 1.09583608347287e-18}, - {23.0, 5.03153504903308e-20, 1.0, 5.266538166725e-20}, - {24.0, 2.2525984149695e-21, 1.0, 2.35003117691919e-21}, - {25.0, 9.3677424515947e-23, 1.0, 9.74327619496943e-23}, - {50.0, 9.83633962945521e-69, 1.0, 9.8677629437617e-69}, - {51.0, 3.13448949497553e-71, 1.0, 3.14233143064882e-71}, - {52.0, 7.82755221928122e-74, 1.0, 7.84193567329055e-74}, - {53.0, 1.43662126065532e-76, 1.0, 1.43834540093295e-76}, - {54.0, 1.72312692517348e-79, 1.0, 1.7241402776278e-79}, - {55.0, 1.01335245432581e-82, 1.0, 1.01335245432581e-82}, + {0.0, 0.155168304750504, 0.155168304750504, 1.0}, + {1.0, 0.29437545000746, 0.449543754757964, 0.844831695249496}, + {2.0, 0.273841321577003, 0.723385076334967, 0.550456245242036}, + {3.0, 0.166488572570786, 0.889873648905753, 0.276614923665033}, + {4.0, 0.0743969744713231, 0.964270623377076, 0.110126351094247}, + {5.0, 0.0260542785784855, 0.990324901955562, 0.0357293766229237}, + {20.0, 3.57101101678792e-16, 1.0, 3.78252101622096e-16}, + {21.0, 2.00551638598312e-17, 1.0, 2.11509999433041e-17}, + {22.0, 1.04317070180562e-18, 1.0, 1.09583608347287e-18}, + {23.0, 5.03153504903308e-20, 1.0, 5.266538166725e-20}, + {24.0, 2.2525984149695e-21, 1.0, 2.35003117691919e-21}, + {25.0, 9.3677424515947e-23, 1.0, 9.74327619496943e-23}, + {50.0, 9.83633962945521e-69, 1.0, 9.8677629437617e-69}, + {51.0, 3.13448949497553e-71, 1.0, 3.14233143064882e-71}, + {52.0, 7.82755221928122e-74, 1.0, 7.84193567329055e-74}, + {53.0, 1.43662126065532e-76, 1.0, 1.43834540093295e-76}, + {54.0, 1.72312692517348e-79, 1.0, 1.7241402776278e-79}, + {55.0, 1.01335245432581e-82, 1.0, 1.01335245432581e-82}, }; testHypergeometricDistributionProbabilities(populationSize, sampleSize, numberOfSucceses, data); } diff --git a/src/test/java/org/apache/commons/math/distribution/IntegerDistributionAbstractTest.java b/src/test/java/org/apache/commons/math/distribution/IntegerDistributionAbstractTest.java index 13db9117c..68b51ea83 100644 --- a/src/test/java/org/apache/commons/math/distribution/IntegerDistributionAbstractTest.java +++ b/src/test/java/org/apache/commons/math/distribution/IntegerDistributionAbstractTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,9 +22,9 @@ import junit.framework.TestCase; * Abstract base class for {@link IntegerDistribution} tests. *

      * To create a concrete test class for an integer distribution implementation, - * implement makeDistribution() to return a distribution instance to use in + * implement makeDistribution() to return a distribution instance to use in * tests and each of the test data generation methods below. In each case, the - * test points and test values arrays returned represent parallel arrays of + * test points and test values arrays returned represent parallel arrays of * inputs and expected values for the distribution returned by makeDistribution(). *

      * makeDensityTestPoints() -- arguments used to test probability density calculation @@ -36,39 +36,39 @@ import junit.framework.TestCase; *

      * To implement additional test cases with different distribution instances and test data, * use the setXxx methods for the instance data in test cases and call the verifyXxx methods - * to verify results. - * + * to verify results. + * * @version $Revision$ $Date$ */ public abstract class IntegerDistributionAbstractTest extends TestCase { - + //-------------------- Private test instance data ------------------------- /** Discrete distribution instance used to perform tests */ private IntegerDistribution distribution; - + /** Tolerance used in comparing expected and returned values */ private double tolerance = 1E-4; - + /** Arguments used to test probability density calculations */ private int[] densityTestPoints; - + /** Values used to test probability density calculations */ private double[] densityTestValues; - + /** Arguments used to test cumulative probability density calculations */ private int[] cumulativeTestPoints; - + /** Values used to test cumulative probability density calculations */ private double[] cumulativeTestValues; - + /** Arguments used to test inverse cumulative probability density calculations */ private double[] inverseCumulativeTestPoints; - + /** Values used to test inverse cumulative probability density calculations */ private int[] inverseCumulativeTestValues; - + //------------------------------------------------------------------------- - + /** * Constructor for IntegerDistributionAbstractTest. * @param name @@ -76,34 +76,34 @@ public abstract class IntegerDistributionAbstractTest extends TestCase { public IntegerDistributionAbstractTest(String name) { super(name); } - + //-------------------- Abstract methods ----------------------------------- - + /** Creates the default discrete distribution instance to use in tests. */ public abstract IntegerDistribution makeDistribution(); - + /** Creates the default probability density test input values */ public abstract int[] makeDensityTestPoints(); - + /** Creates the default probability density test expected values */ public abstract double[] makeDensityTestValues(); - + /** Creates the default cumulative probability density test input values */ public abstract int[] makeCumulativeTestPoints(); - + /** Creates the default cumulative probability density test expected values */ public abstract double[] makeCumulativeTestValues(); - + /** Creates the default inverse cumulative probability test input values */ public abstract double[] makeInverseCumulativeTestPoints(); - + /** Creates the default inverse cumulative probability density test expected values */ public abstract int[] makeInverseCumulativeTestValues(); - + //-------------------- Setup / tear down ---------------------------------- - + /** - * Setup sets all test instance data to default values + * Setup sets all test instance data to default values */ @Override protected void setUp() throws Exception { @@ -114,14 +114,14 @@ public abstract class IntegerDistributionAbstractTest extends TestCase { cumulativeTestPoints = makeCumulativeTestPoints(); cumulativeTestValues = makeCumulativeTestValues(); inverseCumulativeTestPoints = makeInverseCumulativeTestPoints(); - inverseCumulativeTestValues = makeInverseCumulativeTestValues(); + inverseCumulativeTestValues = makeInverseCumulativeTestValues(); } - + /** * Cleans up test instance data */ @Override - protected void tearDown() throws Exception { + protected void tearDown() throws Exception { super.tearDown(); distribution = null; densityTestPoints = null; @@ -129,11 +129,11 @@ public abstract class IntegerDistributionAbstractTest extends TestCase { cumulativeTestPoints = null; cumulativeTestValues = null; inverseCumulativeTestPoints = null; - inverseCumulativeTestValues = null; + inverseCumulativeTestValues = null; } - + //-------------------- Verification methods ------------------------------- - + /** * Verifies that probability density calculations match expected values * using current test instance data @@ -141,36 +141,36 @@ public abstract class IntegerDistributionAbstractTest extends TestCase { protected void verifyDensities() throws Exception { for (int i = 0; i < densityTestPoints.length; i++) { assertEquals("Incorrect density value returned for " + densityTestPoints[i], - densityTestValues[i], + densityTestValues[i], distribution.probability(densityTestPoints[i]), tolerance); - } + } } - + /** * Verifies that cumulative probability density calculations match expected values * using current test instance data - */ + */ protected void verifyCumulativeProbabilities() throws Exception { for (int i = 0; i < cumulativeTestPoints.length; i++) { assertEquals("Incorrect cumulative probability value returned for " + cumulativeTestPoints[i], - cumulativeTestValues[i], + cumulativeTestValues[i], distribution.cumulativeProbability(cumulativeTestPoints[i]), tolerance); - } + } } - - + + /** * Verifies that inverse cumulative probability density calculations match expected values * using current test instance data */ protected void verifyInverseCumulativeProbabilities() throws Exception { for (int i = 0; i < inverseCumulativeTestPoints.length; i++) { - assertEquals("Incorrect inverse cumulative probability value returned for " - + inverseCumulativeTestPoints[i], inverseCumulativeTestValues[i], + assertEquals("Incorrect inverse cumulative probability value returned for " + + inverseCumulativeTestPoints[i], inverseCumulativeTestValues[i], distribution.inverseCumulativeProbability(inverseCumulativeTestPoints[i])); - } + } } - + //------------------------ Default test cases ----------------------------- /** @@ -178,17 +178,17 @@ public abstract class IntegerDistributionAbstractTest extends TestCase { * using default test instance data */ public void testDensities() throws Exception { - verifyDensities(); + verifyDensities(); } - + /** * Verifies that cumulative probability density calculations match expected values * using default test instance data */ public void testCumulativeProbabilities() throws Exception { - verifyCumulativeProbabilities(); + verifyCumulativeProbabilities(); } - + /** * Verifies that floating point arguments are correctly handled by * cumulativeProbablility(-,-) @@ -200,7 +200,7 @@ public abstract class IntegerDistributionAbstractTest extends TestCase { assertEquals( "Incorrect cumulative probability value returned for " + cumulativeTestPoints[i], - cumulativeTestValues[i], + cumulativeTestValues[i], distribution.cumulativeProbability(arg), tolerance); if (i < cumulativeTestPoints.length - 1) { double arg2 = cumulativeTestPoints[i + 1]; @@ -219,33 +219,33 @@ public abstract class IntegerDistributionAbstractTest extends TestCase { cumulativeTestPoints[i + 1]), distribution.cumulativeProbability(arg, arg2), tolerance); } - } + } int one = 1; int ten = 10; int two = 2; double oned = one; double twod = two; double tend = ten; - assertEquals(distribution.cumulativeProbability(one, two), + assertEquals(distribution.cumulativeProbability(one, two), distribution.cumulativeProbability(oned, twod), tolerance); - assertEquals(distribution.cumulativeProbability(one, two), + assertEquals(distribution.cumulativeProbability(one, two), distribution.cumulativeProbability(oned - tolerance, twod + 0.9), tolerance); - assertEquals(distribution.cumulativeProbability(two, ten), + assertEquals(distribution.cumulativeProbability(two, ten), distribution.cumulativeProbability(twod, tend), tolerance); - assertEquals(distribution.cumulativeProbability(two, ten), + assertEquals(distribution.cumulativeProbability(two, ten), distribution.cumulativeProbability(twod - tolerance, tend + 0.9), tolerance); } - + /** * Verifies that inverse cumulative probability density calculations match expected values * using default test instance data */ public void testInverseCumulativeProbabilities() throws Exception { - verifyInverseCumulativeProbabilities(); + verifyInverseCumulativeProbabilities(); } - + /** * Verifies that illegal arguments are correctly handled */ @@ -267,9 +267,9 @@ public abstract class IntegerDistributionAbstractTest extends TestCase { fail("Expecting IllegalArgumentException for p = 2"); } catch (IllegalArgumentException ex) { // expected - } + } } - + //------------------ Getters / Setters for test instance data ----------- /** * @return Returns the cumulativeTestPoints. diff --git a/src/test/java/org/apache/commons/math/distribution/NormalDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/NormalDistributionTest.java index 8f3433c06..0a2204f7b 100644 --- a/src/test/java/org/apache/commons/math/distribution/NormalDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/NormalDistributionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,11 +23,11 @@ import org.apache.commons.math.MathException; * Test cases for NormalDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. - * + * * @version $Revision$ $Date$ */ public class NormalDistributionTest extends ContinuousDistributionAbstractTest { - + /** * Constructor for NormalDistributionTest. * @param arg0 @@ -35,52 +35,52 @@ public class NormalDistributionTest extends ContinuousDistributionAbstractTest public NormalDistributionTest(String arg0) { super(arg0); } - + //-------------- Implementations for abstract methods ----------------------- - + /** Creates the default continuous distribution instance to use in tests. */ @Override public ContinuousDistribution makeDistribution() { return new NormalDistributionImpl(2.1, 1.4); - } - + } + /** Creates the default cumulative probability distribution test input values */ @Override public double[] makeCumulativeTestPoints() { - // quantiles computed using R - return new double[] {-2.226325d, -1.156887d, -0.6439496d, -0.2027951d, 0.3058278d, + // quantiles computed using R + return new double[] {-2.226325d, -1.156887d, -0.6439496d, -0.2027951d, 0.3058278d, 6.426325d, 5.356887d, 4.84395d, 4.402795d, 3.894172d}; } - + /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d, - 0.990d, 0.975d, 0.950d, 0.900d}; + 0.990d, 0.975d, 0.950d, 0.900d}; } - + // --------------------- Override tolerance -------------- @Override protected void setUp() throws Exception { super.setUp(); setTolerance(1E-6); } - + //---------------------------- Additional test cases ------------------------- - + private void verifyQuantiles() throws Exception { NormalDistribution distribution = (NormalDistribution) getDistribution(); double mu = distribution.getMean(); double sigma = distribution.getStandardDeviation(); - setCumulativeTestPoints( new double[] {mu - 2 *sigma, mu - sigma, + setCumulativeTestPoints( new double[] {mu - 2 *sigma, mu - sigma, mu, mu + sigma, mu +2 * sigma, mu +3 * sigma, mu + 4 * sigma, mu + 5 * sigma}); // Quantiles computed using R (same as Mathematica) - setCumulativeTestValues(new double[] {0.02275013, 0.1586553, 0.5, 0.8413447, + setCumulativeTestValues(new double[] {0.02275013, 0.1586553, 0.5, 0.8413447, 0.9772499, 0.9986501, 0.9999683, 0.9999997}); - verifyCumulativeProbabilities(); + verifyCumulativeProbabilities(); } - + public void testQuantiles() throws Exception { verifyQuantiles(); setDistribution(new NormalDistributionImpl(0, 1)); @@ -88,31 +88,31 @@ public class NormalDistributionTest extends ContinuousDistributionAbstractTest setDistribution(new NormalDistributionImpl(0, 0.1)); verifyQuantiles(); } - + public void testInverseCumulativeProbabilityExtremes() throws Exception { setInverseCumulativeTestPoints(new double[] {0, 1}); setInverseCumulativeTestValues( new double[] {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY}); verifyInverseCumulativeProbabilities(); } - + public void testGetMean() { NormalDistribution distribution = (NormalDistribution) getDistribution(); assertEquals(2.1, distribution.getMean(), 0); } - + public void testSetMean() throws Exception { double mu = Math.random(); NormalDistribution distribution = (NormalDistribution) getDistribution(); distribution.setMean(mu); verifyQuantiles(); } - + public void testGetStandardDeviation() { NormalDistribution distribution = (NormalDistribution) getDistribution(); - assertEquals(1.4, distribution.getStandardDeviation(), 0); + assertEquals(1.4, distribution.getStandardDeviation(), 0); } - + public void testSetStandardDeviation() throws Exception { double sigma = 0.1d + Math.random(); NormalDistribution distribution = (NormalDistribution) getDistribution(); @@ -131,7 +131,7 @@ public class NormalDistributionTest extends ContinuousDistributionAbstractTest double [] x = new double[]{-2, -1, 0, 1, 2}; // R 2.5: print(dnorm(c(-2,-1,0,1,2)), digits=10) checkDensity(0, 1, x, new double[]{0.05399096651, 0.24197072452, 0.39894228040, 0.24197072452, 0.05399096651}); - // R 2.5: print(dnorm(c(-2,-1,0,1,2), mean=1.1), digits=10) + // R 2.5: print(dnorm(c(-2,-1,0,1,2), mean=1.1), digits=10) checkDensity(1.1, 1, x, new double[]{0.003266819056,0.043983595980,0.217852177033,0.396952547477,0.266085249899}); } @@ -161,7 +161,7 @@ public class NormalDistributionTest extends ContinuousDistributionAbstractTest assertTrue(lowerTail < 0.00001); assertTrue(upperTail > 0.99999); } - } + } } public void testMath280() throws MathException { diff --git a/src/test/java/org/apache/commons/math/distribution/PascalDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/PascalDistributionTest.java index fa8721576..3a28b7aa7 100644 --- a/src/test/java/org/apache/commons/math/distribution/PascalDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/PascalDistributionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,11 +20,11 @@ package org.apache.commons.math.distribution; * Test cases for PascalDistribution. * Extends IntegerDistributionAbstractTest. See class javadoc for * IntegerDistributionAbstractTest for details. - * + * * @version $Revision$ $Date$ */ public class PascalDistributionTest extends IntegerDistributionAbstractTest { - + /** * Constructor for PascalDistributionTest. * @param name @@ -32,48 +32,48 @@ public class PascalDistributionTest extends IntegerDistributionAbstractTest { public PascalDistributionTest(String name) { super(name); } - + //-------------- Implementations for abstract methods ----------------------- - + /** Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { return new PascalDistributionImpl(10,0.70); } - + /** Creates the default probability density test input values */ @Override public int[] makeDensityTestPoints() { return new int[] {-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; } - + /** Creates the default probability density test expected values */ @Override public double[] makeDensityTestValues() { - return new double[] {0d, 0.02824d, 0.08474d, 0.13982d, + return new double[] {0d, 0.02824d, 0.08474d, 0.13982d, 0.16779d, 0.16359d, 0.1374d, 0.10306d, 0.070673d, 0.04505d, 0.02703d, 0.01540d, 0.0084}; } - + /** Creates the default cumulative probability density test input values */ @Override public int[] makeCumulativeTestPoints() { return makeDensityTestPoints(); } - + /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0d, 0.02824d, 0.11299d, 0.25281d, 0.42060d, 0.58420d, 0.72162d, 0.82468d, 0.89535d, 0.94041d, 0.967446d, 0.98285, 0.99125d}; } - + /** Creates the default inverse cumulative probability test input values */ @Override public double[] makeInverseCumulativeTestPoints() { return new double[] {0, 0.001d, 0.010d, 0.025d, 0.050d, 0.100d, 0.999d, - 0.990d, 0.975d, 0.950d, 0.900d, 1}; + 0.990d, 0.975d, 0.950d, 0.900d, 1}; } - + /** Creates the default inverse cumulative probability density test expected values */ @Override public int[] makeInverseCumulativeTestValues() { @@ -81,7 +81,7 @@ public class PascalDistributionTest extends IntegerDistributionAbstractTest { } //----------------- Additional test cases --------------------------------- - + /** Test degenerate case p = 0 */ public void testDegenerate0() throws Exception { setDistribution(new PascalDistributionImpl(5,0.0d)); @@ -93,9 +93,9 @@ public class PascalDistributionTest extends IntegerDistributionAbstractTest { setInverseCumulativeTestValues(new int[] {Integer.MAX_VALUE - 1, Integer.MAX_VALUE - 1}); verifyDensities(); verifyCumulativeProbabilities(); - verifyInverseCumulativeProbabilities(); + verifyInverseCumulativeProbabilities(); } - + /** Test degenerate case p = 1 */ public void testDegenerate1() throws Exception { setDistribution(new PascalDistributionImpl(5,1.0d)); @@ -107,6 +107,6 @@ public class PascalDistributionTest extends IntegerDistributionAbstractTest { setInverseCumulativeTestValues(new int[] {-1, -1}); verifyDensities(); verifyCumulativeProbabilities(); - verifyInverseCumulativeProbabilities(); + verifyInverseCumulativeProbabilities(); } } diff --git a/src/test/java/org/apache/commons/math/distribution/PoissonDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/PoissonDistributionTest.java index d7165c8b4..d1449371a 100644 --- a/src/test/java/org/apache/commons/math/distribution/PoissonDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/PoissonDistributionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +20,7 @@ import org.apache.commons.math.MathException; /** * PoissonDistributionTest - * + * * @version $Revision$ $Date$ */ public class PoissonDistributionTest extends IntegerDistributionAbstractTest { @@ -39,15 +39,15 @@ public class PoissonDistributionTest extends IntegerDistributionAbstractTest { setTolerance(1e-12); } - /** - * Creates the default discrete distribution instance to use in tests. + /** + * Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { - return new PoissonDistributionImpl(DEFAULT_TEST_POISSON_PARAMETER); + return new PoissonDistributionImpl(DEFAULT_TEST_POISSON_PARAMETER); } - /** + /** * Creates the default probability density test input values. */ @Override @@ -62,7 +62,7 @@ public class PoissonDistributionTest extends IntegerDistributionAbstractTest { @Override public double[] makeDensityTestValues() { return new double[] { 0d, 0.0183156388887d, 0.073262555555d, - 0.14652511111d, 0.195366814813d, 0.195366814813, + 0.14652511111d, 0.195366814813d, 0.195366814813, 0.156293451851d, 0.00529247667642d, 8.27746364655e-09}; } @@ -79,20 +79,20 @@ public class PoissonDistributionTest extends IntegerDistributionAbstractTest { */ @Override public double[] makeCumulativeTestValues() { - return new double[] { 0d, 0.0183156388887d, 0.0915781944437d, + return new double[] { 0d, 0.0183156388887d, 0.0915781944437d, 0.238103305554d, 0.433470120367d, 0.62883693518, 0.78513038703d, 0.99716023388d, 0.999999998077 }; } - /** + /** * Creates the default inverse cumulative probability test input values. * Increased 3rd and 7th values slightly as computed cumulative - * probabilities for corresponding values exceeds the target value (still + * probabilities for corresponding values exceeds the target value (still * within tolerance). */ @Override public double[] makeInverseCumulativeTestPoints() { - return new double[] { 0d, 0.018315638889d, 0.0915781944437d, + return new double[] { 0d, 0.018315638889d, 0.0915781944437d, 0.238103305554d, 0.433470120367d, 0.62883693518, 0.78513038704d, 0.99716023388d, 0.999999998077 }; } @@ -130,7 +130,7 @@ public class PoissonDistributionTest extends IntegerDistributionAbstractTest { assertEquals(Integer.MAX_VALUE, dist.inverseCumulativeProbability(1.0d)); assertEquals(-1, dist.inverseCumulativeProbability(0d)); } - + public void testMean() { PoissonDistribution dist = new PoissonDistributionImpl(DEFAULT_TEST_POISSON_PARAMETER); try { @@ -138,17 +138,17 @@ public class PoissonDistributionTest extends IntegerDistributionAbstractTest { fail("negative mean. IllegalArgumentException expected"); } catch(IllegalArgumentException ex) { } - + dist.setMean(10.0); assertEquals(10.0, dist.getMean(), 0.0); } - + public void testLargeMeanCumulativeProbability() { PoissonDistribution dist = new PoissonDistributionImpl(1.0); double mean = 1.0; while (mean <= 10000000.0) { dist.setMean(mean); - + double x = mean * 2.0; double dx = x / 10.0; while (x >= 0) { @@ -159,17 +159,17 @@ public class PoissonDistributionTest extends IntegerDistributionAbstractTest { } x -= dx; } - + mean *= 10.0; } } - + public void testLargeMeanInverseCumulativeProbability() { PoissonDistribution dist = new PoissonDistributionImpl(1.0); double mean = 1.0; while (mean <= 10000000.0) { dist.setMean(mean); - + double p = 0.1; double dp = p; while (p < 1.0) { @@ -180,8 +180,8 @@ public class PoissonDistributionTest extends IntegerDistributionAbstractTest { } p += dp; } - + mean *= 10.0; } } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/math/distribution/WeibullDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/WeibullDistributionTest.java index ee06df851..98d39a7ff 100644 --- a/src/test/java/org/apache/commons/math/distribution/WeibullDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/WeibullDistributionTest.java @@ -21,11 +21,11 @@ package org.apache.commons.math.distribution; * Test cases for WeibullDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. - * + * * @version $Revision$ $Date$ */ public class WeibullDistributionTest extends ContinuousDistributionAbstractTest { - + /** * Constructor for CauchyDistributionTest. * @param arg0 @@ -33,54 +33,54 @@ public class WeibullDistributionTest extends ContinuousDistributionAbstractTest public WeibullDistributionTest(String arg0) { super(arg0); } - + //-------------- Implementations for abstract methods ----------------------- - + /** Creates the default continuous distribution instance to use in tests. */ @Override public ContinuousDistribution makeDistribution() { return new WeibullDistributionImpl(1.2, 2.1); - } - + } + /** Creates the default cumulative probability distribution test input values */ @Override public double[] makeCumulativeTestPoints() { - // quantiles computed using Mathematica + // quantiles computed using Mathematica return new double[] {0.00664355181d, 0.04543282833d, 0.09811627374d, 0.1767135246d, 0.3219468654d, 4.207902826d, 5.23968437d, 6.232056007d, 7.497630467d, 10.51154969d}; } - + /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.900d, 0.950d, 0.975d, 0.990d, 0.999d}; } - + //---------------------------- Additional test cases ------------------------- - + public void testInverseCumulativeProbabilityExtremes() throws Exception { setInverseCumulativeTestPoints(new double[] {0.0, 1.0}); setInverseCumulativeTestValues( new double[] {0.0, Double.POSITIVE_INFINITY}); verifyInverseCumulativeProbabilities(); } - + public void testAlpha() { WeibullDistribution distribution = (WeibullDistribution) getDistribution(); double expected = Math.random(); distribution.setShape(expected); assertEquals(expected, distribution.getShape(), 0.0); } - + public void testBeta() { WeibullDistribution distribution = (WeibullDistribution) getDistribution(); double expected = Math.random(); distribution.setScale(expected); assertEquals(expected, distribution.getScale(), 0.0); } - + public void testSetAlpha() { WeibullDistribution distribution = (WeibullDistribution) getDistribution(); try { @@ -89,7 +89,7 @@ public class WeibullDistributionTest extends ContinuousDistributionAbstractTest } catch (IllegalArgumentException ex) { // success } - + try { distribution.setShape(-1.0); fail("Can not have negative alpha."); @@ -97,7 +97,7 @@ public class WeibullDistributionTest extends ContinuousDistributionAbstractTest // success } } - + public void testSetBeta() { WeibullDistribution distribution = (WeibullDistribution) getDistribution(); try { @@ -106,7 +106,7 @@ public class WeibullDistributionTest extends ContinuousDistributionAbstractTest } catch (IllegalArgumentException ex) { // success } - + try { distribution.setScale(-1.0); fail("Can not have negative beta."); diff --git a/src/test/java/org/apache/commons/math/distribution/ZipfDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/ZipfDistributionTest.java index a641b5396..08b867571 100644 --- a/src/test/java/org/apache/commons/math/distribution/ZipfDistributionTest.java +++ b/src/test/java/org/apache/commons/math/distribution/ZipfDistributionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,58 +21,58 @@ package org.apache.commons.math.distribution; * Test cases for {@link ZipfDistribution}. * Extends IntegerDistributionAbstractTest. See class javadoc for * IntegerDistributionAbstractTest for details. - * + * * @version $Revision$ $Date$ */ public class ZipfDistributionTest extends IntegerDistributionAbstractTest { public ZipfDistributionTest(String name) { super(name); } - + //-------------- Implementations for abstract methods ----------------------- - + /** Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { return new ZipfDistributionImpl(10, 1); } - + /** Creates the default probability density test input values */ @Override public int[] makeDensityTestPoints() { return new int[] {-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; } - + /** Creates the default probability density test expected values */ @Override public double[] makeDensityTestValues() { - return new double[] {0d, 0d, 0.3414d, 0.1707d, 0.1138d, 0.0854d, 0.0683d, + return new double[] {0d, 0d, 0.3414d, 0.1707d, 0.1138d, 0.0854d, 0.0683d, 0.0569d, 0.0488d, 0.0427d, 0.0379d, 0.0341d, 0d}; } - + /** Creates the default cumulative probability density test input values */ @Override public int[] makeCumulativeTestPoints() { return makeDensityTestPoints(); } - + /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0d, 0.0000d, 0.3414d, 0.5121d, 0.6259d, 0.7113d, 0.7796d, 0.8365d, 0.8852d, 0.9279d, 0.9659d, 1d, 1d}; } - + /** Creates the default inverse cumulative probability test input values */ @Override public double[] makeInverseCumulativeTestPoints() { return new double[] {0, 0.001d, 0.010d, 0.025d, 0.050d, 0.3414d, 0.3415d, 0.999d, - 0.990d, 0.975d, 0.950d, 0.900d, 1}; + 0.990d, 0.975d, 0.950d, 0.900d, 1}; } - + /** Creates the default inverse cumulative probability density test expected values */ @Override public int[] makeInverseCumulativeTestValues() { return new int[] {0, 0, 0, 0, 0, 0, 1, 9, 9, 9, 8, 7, 10}; } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/math/estimation/GaussNewtonEstimatorTest.java b/src/test/java/org/apache/commons/math/estimation/GaussNewtonEstimatorTest.java index 2bf3f013b..8f2cf52b9 100644 --- a/src/test/java/org/apache/commons/math/estimation/GaussNewtonEstimatorTest.java +++ b/src/test/java/org/apache/commons/math/estimation/GaussNewtonEstimatorTest.java @@ -27,7 +27,7 @@ import junit.framework.TestSuite; /** *

      Some of the unit tests are re-implementations of the MINPACK file17 and file22 test files. + * href="http://www.netlib.org/minpack/ex/file22">file22 test files. * The redistribution policy for MINPACK is available here, for * convenience, it is reproduced below.

      diff --git a/src/test/java/org/apache/commons/math/estimation/LevenbergMarquardtEstimatorTest.java b/src/test/java/org/apache/commons/math/estimation/LevenbergMarquardtEstimatorTest.java index 9423542f3..0f7451954 100644 --- a/src/test/java/org/apache/commons/math/estimation/LevenbergMarquardtEstimatorTest.java +++ b/src/test/java/org/apache/commons/math/estimation/LevenbergMarquardtEstimatorTest.java @@ -27,7 +27,7 @@ import junit.framework.TestSuite; /** *

      Some of the unit tests are re-implementations of the MINPACK file17 and file22 test files. + * href="http://www.netlib.org/minpack/ex/file22">file22 test files. * The redistribution policy for MINPACK is available here, for * convenience, it is reproduced below.

      @@ -515,7 +515,7 @@ public class LevenbergMarquardtEstimatorTest double[] errors = estimator.guessParametersErrors(circle); assertEquals(1.384, errors[0], 0.001); assertEquals(0.905, errors[1], 0.001); - + // add perfect measurements and check errors are reduced double cx = circle.getX(); double cy = circle.getY(); @@ -622,7 +622,7 @@ public class LevenbergMarquardtEstimatorTest } return set.toArray(new EstimatedParameter[set.size()]); } - + private LinearMeasurement[] measurements; } diff --git a/src/test/java/org/apache/commons/math/estimation/MinpackTest.java b/src/test/java/org/apache/commons/math/estimation/MinpackTest.java index 0271c3702..2297ab1d3 100644 --- a/src/test/java/org/apache/commons/math/estimation/MinpackTest.java +++ b/src/test/java/org/apache/commons/math/estimation/MinpackTest.java @@ -30,7 +30,7 @@ import junit.framework.*; /** *

      Some of the unit tests are re-implementations of the MINPACK file17 and file22 test files. + * href="http://www.netlib.org/minpack/ex/file22">file22 test files. * The redistribution policy for MINPACK is available here, for * convenience, it is reproduced below.

      @@ -133,7 +133,7 @@ public class MinpackTest minpackTest(new HelicalValleyFunction(new double[] { -100.0, 0.0, 0.0}, 991.261822123701), false); } - + public void testMinpackPowellSingular() { minpackTest(new PowellSingularFunction(new double[] { 3.0, -1.0, 0.0, 1.0 }, 14.6628782986152), false); @@ -142,7 +142,7 @@ public class MinpackTest minpackTest(new PowellSingularFunction(new double[] { 300.0, -100.0, 0.0, 100.0 }, 126887.903284750), false); } - + public void testMinpackFreudensteinRoth() { minpackTest(new FreudensteinRothFunction(new double[] { 0.5, -2.0 }, 20.0124960961895, 6.99887517584575, @@ -163,7 +163,7 @@ public class MinpackTest -0.89680510749204 }), false); } - + public void testMinpackBard() { minpackTest(new BardFunction(1.0, 6.45613629515967, 0.0906359603390466, new double[] { @@ -184,7 +184,7 @@ public class MinpackTest -164464906.857771 }), false); } - + public void testMinpackKowalikOsborne() { minpackTest(new KowalikOsborneFunction(new double[] { 0.25, 0.39, 0.415, 0.39 }, 0.0728915102882945, @@ -214,7 +214,7 @@ public class MinpackTest 0.134575665392506 }), true); } - + public void testMinpackMeyer() { minpackTest(new MeyerFunction(new double[] { 0.02, 4000.0, 250.0 }, 41153.4665543031, 9.37794514651874, @@ -231,9 +231,9 @@ public class MinpackTest 901.268527953801 }), true); } - + public void testMinpackWatson() { - + minpackTest(new WatsonFunction(6, 0.0, 5.47722557505166, 0.0478295939097601, new double[] { @@ -316,12 +316,12 @@ public class MinpackTest }), false); } - + public void testMinpackBox3Dimensional() { minpackTest(new Box3DimensionalFunction(10, new double[] { 0.0, 10.0, 20.0 }, 32.1115837449572), false); } - + public void testMinpackJennrichSampson() { minpackTest(new JennrichSampsonFunction(10, new double[] { 0.3, 0.4 }, 64.5856498144943, 11.1517793413499, @@ -353,7 +353,7 @@ public class MinpackTest -0.403688070279258, 0.236665033746463 }), false); } - + public void testMinpackChebyquad() { minpackTest(new ChebyquadFunction(1, 8, 1.0, 1.88623796907732, 1.88623796907732, @@ -391,7 +391,7 @@ public class MinpackTest 0.833291216194063, 0.940379732824644 }), false); } - + public void testMinpackBrownAlmostLinear() { minpackTest(new BrownAlmostLinearFunction(10, 0.5, 16.5302162063499, 0.0, @@ -410,7 +410,7 @@ public class MinpackTest 0.979430303349865, 0.979430303349865, 0.979430303349865, 0.979430303349865, 0.979430303349865, 1.20569696650135 - }), false); + }), false); minpackTest(new BrownAlmostLinearFunction(10, 50.0, 0.9765625e17, 0.0, new double[] { @@ -459,7 +459,7 @@ public class MinpackTest 0.999999999999121 }), false); } - + public void testMinpackOsborne1() { minpackTest(new Osborne1Function(new double[] { 0.5, 1.5, -1.0, 0.01, 0.02, }, 0.937564021037838, 0.00739249260904843, @@ -469,9 +469,9 @@ public class MinpackTest 0.0221227011813076 }), false); } - + public void testMinpackOsborne2() { - + minpackTest(new Osborne2Function(new double[] { 1.3, 0.65, 0.65, 0.7, 0.6, 3.0, 5.0, 7.0, 2.0, 4.5, 5.5 @@ -505,7 +505,7 @@ public class MinpackTest } private static abstract class MinpackFunction implements EstimationProblem { - + protected MinpackFunction(int m, double[] startParams, double theoreticalStartCost, @@ -564,7 +564,7 @@ public class MinpackTest } return true; } - + public WeightedMeasurement[] getMeasurements() { WeightedMeasurement[] measurements = new WeightedMeasurement[m]; for (int i = 0; i < m; ++i) { @@ -1043,7 +1043,7 @@ public class MinpackTest 34780.0, 28610.0, 23650.0, 19630.0, 16370.0, 13720.0, 11540.0, 9744.0, 8261.0, 7030.0, 6005.0, 5147.0, - 4427.0, 3820.0, 3307.0, 2872.0 + 4427.0, 3820.0, 3307.0, 2872.0 }; } diff --git a/src/test/java/org/apache/commons/math/fraction/BigFractionFormatTest.java b/src/test/java/org/apache/commons/math/fraction/BigFractionFormatTest.java index e7697bec4..6fc73c913 100644 --- a/src/test/java/org/apache/commons/math/fraction/BigFractionFormatTest.java +++ b/src/test/java/org/apache/commons/math/fraction/BigFractionFormatTest.java @@ -26,7 +26,7 @@ import java.util.Locale; import junit.framework.TestCase; public class BigFractionFormatTest extends TestCase { - + BigFractionFormat properFormat = null; BigFractionFormat improperFormat = null; @@ -39,12 +39,12 @@ public class BigFractionFormatTest extends TestCase { properFormat = BigFractionFormat.getProperInstance(getLocale()); improperFormat = BigFractionFormat.getImproperInstance(getLocale()); } - + public void testFormat() { BigFraction c = new BigFraction(1, 2); String expected = "1 / 2"; - - String actual = properFormat.format(c); + + String actual = properFormat.format(c); assertEquals(expected, actual); actual = improperFormat.format(c); @@ -55,10 +55,10 @@ public class BigFractionFormatTest extends TestCase { BigFraction c = new BigFraction(-1, 2); String expected = "-1 / 2"; - String actual = properFormat.format(c); + String actual = properFormat.format(c); assertEquals(expected, actual); - actual = improperFormat.format(c); + actual = improperFormat.format(c); assertEquals(expected, actual); } @@ -66,33 +66,33 @@ public class BigFractionFormatTest extends TestCase { BigFraction c = new BigFraction(0, 1); String expected = "0 / 1"; - String actual = properFormat.format(c); + String actual = properFormat.format(c); assertEquals(expected, actual); - actual = improperFormat.format(c); + actual = improperFormat.format(c); assertEquals(expected, actual); } - + public void testFormatImproper() { BigFraction c = new BigFraction(5, 3); - String actual = properFormat.format(c); + String actual = properFormat.format(c); assertEquals("1 2 / 3", actual); - actual = improperFormat.format(c); + actual = improperFormat.format(c); assertEquals("5 / 3", actual); } - + public void testFormatImproperNegative() { BigFraction c = new BigFraction(-5, 3); - String actual = properFormat.format(c); + String actual = properFormat.format(c); assertEquals("-1 2 / 3", actual); - actual = improperFormat.format(c); + actual = improperFormat.format(c); assertEquals("-5 / 3", actual); } - + public void testParse() { String source = "1 / 2"; @@ -101,7 +101,7 @@ public class BigFractionFormatTest extends TestCase { assertNotNull(c); assertEquals(BigInteger.ONE, c.getNumerator()); assertEquals(BigInteger.valueOf(2l), c.getDenominator()); - + c = improperFormat.parse(source); assertNotNull(c); assertEquals(BigInteger.ONE, c.getNumerator()); @@ -110,7 +110,7 @@ public class BigFractionFormatTest extends TestCase { fail(ex.getMessage()); } } - + public void testParseInteger() { String source = "10"; try { @@ -130,7 +130,7 @@ public class BigFractionFormatTest extends TestCase { fail(ex.getMessage()); } } - + public void testParseInvalid() { String source = "a"; String msg = "should not be able to parse '10 / a'."; @@ -147,7 +147,7 @@ public class BigFractionFormatTest extends TestCase { // success } } - + public void testParseInvalidDenominator() { String source = "10 / a"; String msg = "should not be able to parse '10 / a'."; @@ -164,7 +164,7 @@ public class BigFractionFormatTest extends TestCase { // success } } - + public void testParseNegative() { try { @@ -173,7 +173,7 @@ public class BigFractionFormatTest extends TestCase { assertNotNull(c); assertEquals(-1, c.getNumeratorAsInt()); assertEquals(2, c.getDenominatorAsInt()); - + c = improperFormat.parse(source); assertNotNull(c); assertEquals(-1, c.getNumeratorAsInt()); @@ -184,7 +184,7 @@ public class BigFractionFormatTest extends TestCase { assertNotNull(c); assertEquals(-1, c.getNumeratorAsInt()); assertEquals(2, c.getDenominatorAsInt()); - + c = improperFormat.parse(source); assertNotNull(c); assertEquals(-1, c.getNumeratorAsInt()); @@ -193,7 +193,7 @@ public class BigFractionFormatTest extends TestCase { fail(ex.getMessage()); } } - + public void testParseProper() { String source = "1 2 / 3"; @@ -205,7 +205,7 @@ public class BigFractionFormatTest extends TestCase { } catch (ParseException ex) { fail(ex.getMessage()); } - + try { improperFormat.parse(source); fail("invalid improper fraction."); @@ -213,7 +213,7 @@ public class BigFractionFormatTest extends TestCase { // success } } - + public void testParseProperNegative() { String source = "-1 2 / 3"; try { @@ -224,7 +224,7 @@ public class BigFractionFormatTest extends TestCase { } catch (ParseException ex) { fail(ex.getMessage()); } - + try { improperFormat.parse(source); fail("invalid improper fraction."); @@ -232,7 +232,7 @@ public class BigFractionFormatTest extends TestCase { // success } } - + public void testParseProperInvalidMinus() { String source = "2 -2 / 3"; try { @@ -267,7 +267,7 @@ public class BigFractionFormatTest extends TestCase { new BigDecimal("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068"); assertEquals(pi, f1.bigDecimalValue(99, BigDecimal.ROUND_HALF_EVEN)); } - + public void testNumeratorFormat() { NumberFormat old = properFormat.getNumeratorFormat(); NumberFormat nf = NumberFormat.getInstance(); @@ -283,7 +283,7 @@ public class BigFractionFormatTest extends TestCase { assertEquals(nf, improperFormat.getNumeratorFormat()); improperFormat.setNumeratorFormat(old); } - + public void testDenominatorFormat() { NumberFormat old = properFormat.getDenominatorFormat(); NumberFormat nf = NumberFormat.getInstance(); @@ -299,10 +299,10 @@ public class BigFractionFormatTest extends TestCase { assertEquals(nf, improperFormat.getDenominatorFormat()); improperFormat.setDenominatorFormat(old); } - + public void testWholeFormat() { ProperBigFractionFormat format = (ProperBigFractionFormat)properFormat; - + NumberFormat old = format.getWholeFormat(); NumberFormat nf = NumberFormat.getInstance(); nf.setParseIntegerOnly(true); @@ -310,11 +310,11 @@ public class BigFractionFormatTest extends TestCase { assertEquals(nf, format.getWholeFormat()); format.setWholeFormat(old); } - + public void testLongFormat() { assertEquals("10 / 1", improperFormat.format(10l)); } - + public void testDoubleFormat() { assertEquals("1 / 16", improperFormat.format(0.0625)); } diff --git a/src/test/java/org/apache/commons/math/fraction/FractionFormatTest.java b/src/test/java/org/apache/commons/math/fraction/FractionFormatTest.java index 360b41ac2..116b97bdb 100644 --- a/src/test/java/org/apache/commons/math/fraction/FractionFormatTest.java +++ b/src/test/java/org/apache/commons/math/fraction/FractionFormatTest.java @@ -24,7 +24,7 @@ import java.util.Locale; import junit.framework.TestCase; public class FractionFormatTest extends TestCase { - + FractionFormat properFormat = null; FractionFormat improperFormat = null; @@ -37,12 +37,12 @@ public class FractionFormatTest extends TestCase { properFormat = FractionFormat.getProperInstance(getLocale()); improperFormat = FractionFormat.getImproperInstance(getLocale()); } - + public void testFormat() { Fraction c = new Fraction(1, 2); String expected = "1 / 2"; - - String actual = properFormat.format(c); + + String actual = properFormat.format(c); assertEquals(expected, actual); actual = improperFormat.format(c); @@ -53,10 +53,10 @@ public class FractionFormatTest extends TestCase { Fraction c = new Fraction(-1, 2); String expected = "-1 / 2"; - String actual = properFormat.format(c); + String actual = properFormat.format(c); assertEquals(expected, actual); - actual = improperFormat.format(c); + actual = improperFormat.format(c); assertEquals(expected, actual); } @@ -64,33 +64,33 @@ public class FractionFormatTest extends TestCase { Fraction c = new Fraction(0, 1); String expected = "0 / 1"; - String actual = properFormat.format(c); + String actual = properFormat.format(c); assertEquals(expected, actual); - actual = improperFormat.format(c); + actual = improperFormat.format(c); assertEquals(expected, actual); } - + public void testFormatImproper() { Fraction c = new Fraction(5, 3); - String actual = properFormat.format(c); + String actual = properFormat.format(c); assertEquals("1 2 / 3", actual); - actual = improperFormat.format(c); + actual = improperFormat.format(c); assertEquals("5 / 3", actual); } - + public void testFormatImproperNegative() { Fraction c = new Fraction(-5, 3); - String actual = properFormat.format(c); + String actual = properFormat.format(c); assertEquals("-1 2 / 3", actual); - actual = improperFormat.format(c); + actual = improperFormat.format(c); assertEquals("-5 / 3", actual); } - + public void testParse() { String source = "1 / 2"; @@ -99,7 +99,7 @@ public class FractionFormatTest extends TestCase { assertNotNull(c); assertEquals(1, c.getNumerator()); assertEquals(2, c.getDenominator()); - + c = improperFormat.parse(source); assertNotNull(c); assertEquals(1, c.getNumerator()); @@ -108,7 +108,7 @@ public class FractionFormatTest extends TestCase { fail(ex.getMessage()); } } - + public void testParseInteger() { String source = "10"; try { @@ -128,7 +128,7 @@ public class FractionFormatTest extends TestCase { fail(ex.getMessage()); } } - + public void testParseInvalid() { String source = "a"; String msg = "should not be able to parse '10 / a'."; @@ -145,7 +145,7 @@ public class FractionFormatTest extends TestCase { // success } } - + public void testParseInvalidDenominator() { String source = "10 / a"; String msg = "should not be able to parse '10 / a'."; @@ -162,7 +162,7 @@ public class FractionFormatTest extends TestCase { // success } } - + public void testParseNegative() { try { @@ -171,7 +171,7 @@ public class FractionFormatTest extends TestCase { assertNotNull(c); assertEquals(-1, c.getNumerator()); assertEquals(2, c.getDenominator()); - + c = improperFormat.parse(source); assertNotNull(c); assertEquals(-1, c.getNumerator()); @@ -182,7 +182,7 @@ public class FractionFormatTest extends TestCase { assertNotNull(c); assertEquals(-1, c.getNumerator()); assertEquals(2, c.getDenominator()); - + c = improperFormat.parse(source); assertNotNull(c); assertEquals(-1, c.getNumerator()); @@ -191,7 +191,7 @@ public class FractionFormatTest extends TestCase { fail(ex.getMessage()); } } - + public void testParseProper() { String source = "1 2 / 3"; @@ -203,7 +203,7 @@ public class FractionFormatTest extends TestCase { } catch (ParseException ex) { fail(ex.getMessage()); } - + try { improperFormat.parse(source); fail("invalid improper fraction."); @@ -211,7 +211,7 @@ public class FractionFormatTest extends TestCase { // success } } - + public void testParseProperNegative() { String source = "-1 2 / 3"; try { @@ -222,7 +222,7 @@ public class FractionFormatTest extends TestCase { } catch (ParseException ex) { fail(ex.getMessage()); } - + try { improperFormat.parse(source); fail("invalid improper fraction."); @@ -230,7 +230,7 @@ public class FractionFormatTest extends TestCase { // success } } - + public void testParseProperInvalidMinus() { String source = "2 -2 / 3"; try { @@ -247,7 +247,7 @@ public class FractionFormatTest extends TestCase { // expected } } - + public void testNumeratorFormat() { NumberFormat old = properFormat.getNumeratorFormat(); NumberFormat nf = NumberFormat.getInstance(); @@ -263,7 +263,7 @@ public class FractionFormatTest extends TestCase { assertEquals(nf, improperFormat.getNumeratorFormat()); improperFormat.setNumeratorFormat(old); } - + public void testDenominatorFormat() { NumberFormat old = properFormat.getDenominatorFormat(); NumberFormat nf = NumberFormat.getInstance(); @@ -279,10 +279,10 @@ public class FractionFormatTest extends TestCase { assertEquals(nf, improperFormat.getDenominatorFormat()); improperFormat.setDenominatorFormat(old); } - + public void testWholeFormat() { ProperFractionFormat format = (ProperFractionFormat)properFormat; - + NumberFormat old = format.getWholeFormat(); NumberFormat nf = NumberFormat.getInstance(); nf.setParseIntegerOnly(true); @@ -290,11 +290,11 @@ public class FractionFormatTest extends TestCase { assertEquals(nf, format.getWholeFormat()); format.setWholeFormat(old); } - + public void testLongFormat() { assertEquals("10 / 1", improperFormat.format(10l)); } - + public void testDoubleFormat() { assertEquals("355 / 113", improperFormat.format(Math.PI)); } diff --git a/src/test/java/org/apache/commons/math/fraction/FractionTest.java b/src/test/java/org/apache/commons/math/fraction/FractionTest.java index 8cc4a042a..ab77dde32 100644 --- a/src/test/java/org/apache/commons/math/fraction/FractionTest.java +++ b/src/test/java/org/apache/commons/math/fraction/FractionTest.java @@ -30,7 +30,7 @@ public class FractionTest extends TestCase { assertEquals(expectedNumerator, actual.getNumerator()); assertEquals(expectedDenominator, actual.getDenominator()); } - + public void testConstructor() { assertFraction(0, 1, new Fraction(0, 1)); assertFraction(0, 1, new Fraction(0, 2)); @@ -41,7 +41,7 @@ public class FractionTest extends TestCase { assertFraction(-1, 2, new Fraction(1, -2)); assertFraction(-1, 2, new Fraction(-2, 4)); assertFraction(-1, 2, new Fraction(2, -4)); - + // overflow try { new Fraction(Integer.MIN_VALUE, -1); @@ -55,11 +55,11 @@ public class FractionTest extends TestCase { } catch (ArithmeticException ex) { // success } - try { + try { assertFraction(0, 1, new Fraction(0.00000000000001)); assertFraction(2, 5, new Fraction(0.40000000000001)); assertFraction(15, 1, new Fraction(15.0000000000001)); - + } catch (ConvergenceException ex) { fail(ex.getMessage()); } @@ -165,7 +165,7 @@ public class FractionTest extends TestCase { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Fraction third = new Fraction(1, 2); - + assertEquals(0, first.compareTo(first)); assertEquals(0, first.compareTo(third)); assertEquals(1, first.compareTo(second)); @@ -180,7 +180,7 @@ public class FractionTest extends TestCase { assertEquals( 1, pi2.compareTo(pi1)); assertEquals(0.0, pi1.doubleValue() - pi2.doubleValue(), 1.0e-20); } - + public void testDoubleValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); @@ -188,7 +188,7 @@ public class FractionTest extends TestCase { assertEquals(0.5, first.doubleValue(), 0.0); assertEquals(1.0 / 3.0, second.doubleValue(), 0.0); } - + public void testFloatValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); @@ -196,7 +196,7 @@ public class FractionTest extends TestCase { assertEquals(0.5f, first.floatValue(), 0.0f); assertEquals((float)(1.0 / 3.0), second.floatValue(), 0.0f); } - + public void testIntValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); @@ -204,7 +204,7 @@ public class FractionTest extends TestCase { assertEquals(0, first.intValue()); assertEquals(1, second.intValue()); } - + public void testLongValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); @@ -212,7 +212,7 @@ public class FractionTest extends TestCase { assertEquals(0L, first.longValue()); assertEquals(1L, second.longValue()); } - + public void testConstructorDouble() { try { assertFraction(1, 2, new Fraction(0.5)); @@ -227,35 +227,35 @@ public class FractionTest extends TestCase { fail(ex.getMessage()); } } - + public void testAbs() { Fraction a = new Fraction(10, 21); Fraction b = new Fraction(-10, 21); Fraction c = new Fraction(10, -21); - + assertFraction(10, 21, a.abs()); assertFraction(10, 21, b.abs()); assertFraction(10, 21, c.abs()); } - + public void testReciprocal() { Fraction f = null; - + f = new Fraction(50, 75); f = f.reciprocal(); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); - + f = new Fraction(4, 3); f = f.reciprocal(); assertEquals(3, f.getNumerator()); assertEquals(4, f.getDenominator()); - + f = new Fraction(-15, 47); f = f.reciprocal(); assertEquals(-47, f.getNumerator()); assertEquals(15, f.getDenominator()); - + f = new Fraction(0, 3); try { f = f.reciprocal(); @@ -268,15 +268,15 @@ public class FractionTest extends TestCase { assertEquals(1, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); } - + public void testNegate() { Fraction f = null; - + f = new Fraction(50, 75); f = f.negate(); assertEquals(-2, f.getNumerator()); assertEquals(3, f.getDenominator()); - + f = new Fraction(-50, 75); f = f.negate(); assertEquals(2, f.getNumerator()); @@ -294,16 +294,16 @@ public class FractionTest extends TestCase { fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } - + public void testAdd() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); - + assertFraction(1, 1, a.add(a)); assertFraction(7, 6, a.add(b)); assertFraction(7, 6, b.add(a)); assertFraction(4, 3, b.add(b)); - + Fraction f1 = new Fraction(Integer.MAX_VALUE - 1, 1); Fraction f2 = Fraction.ONE; Fraction f = f1.add(f2); @@ -312,18 +312,18 @@ public class FractionTest extends TestCase { f = f1.add(1); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); - + f1 = new Fraction(-1, 13*13*2*2); f2 = new Fraction(-2, 13*17*2); f = f1.add(f2); assertEquals(13*13*17*2*2, f.getDenominator()); assertEquals(-17 - 2*13*2, f.getNumerator()); - + try { f.add(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} - + // if this fraction is added naively, it will overflow. // check that it doesn't. f1 = new Fraction(1,32768*3); @@ -337,18 +337,18 @@ public class FractionTest extends TestCase { f = f1.add(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); - + f1 = new Fraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); - + try { f = f.add(Fraction.ONE); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} - + // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(-1,5); @@ -356,19 +356,19 @@ public class FractionTest extends TestCase { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} - + try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} - + try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} - + f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { @@ -376,39 +376,39 @@ public class FractionTest extends TestCase { fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } - + public void testDivide() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); - + assertFraction(1, 1, a.divide(a)); assertFraction(3, 4, a.divide(b)); assertFraction(4, 3, b.divide(a)); assertFraction(1, 1, b.divide(b)); - + Fraction f1 = new Fraction(3, 5); Fraction f2 = Fraction.ZERO; try { f1.divide(f2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} - + f1 = new Fraction(0, 5); f2 = new Fraction(2, 7); Fraction f = f1.divide(f2); assertSame(Fraction.ZERO, f); - + f1 = new Fraction(2, 7); f2 = Fraction.ONE; f = f1.divide(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); - + f1 = new Fraction(1, Integer.MAX_VALUE); - f = f1.divide(f1); + f = f1.divide(f1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); - + f1 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f2); @@ -419,7 +419,7 @@ public class FractionTest extends TestCase { f.divide(null); fail("IllegalArgumentException"); } catch (IllegalArgumentException ex) {} - + try { f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow @@ -437,16 +437,16 @@ public class FractionTest extends TestCase { assertEquals(175, f.getDenominator()); } - + public void testMultiply() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); - + assertFraction(1, 4, a.multiply(a)); assertFraction(1, 3, a.multiply(b)); assertFraction(1, 3, b.multiply(a)); assertFraction(4, 9, b.multiply(b)); - + Fraction f1 = new Fraction(Integer.MAX_VALUE, 1); Fraction f2 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); Fraction f = f1.multiply(f2); @@ -463,22 +463,22 @@ public class FractionTest extends TestCase { assertEquals(18, f.getNumerator()); assertEquals(7, f.getDenominator()); } - + public void testSubtract() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); - + assertFraction(0, 1, a.subtract(a)); assertFraction(-1, 6, a.subtract(b)); assertFraction(1, 6, b.subtract(a)); assertFraction(0, 1, b.subtract(b)); - + Fraction f = new Fraction(1,1); try { f.subtract(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} - + // if this fraction is subtracted naively, it will overflow. // check that it doesn't. Fraction f1 = new Fraction(1,32768*3); @@ -492,7 +492,7 @@ public class FractionTest extends TestCase { f = f1.subtract(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); - + f1 = new Fraction(Integer.MAX_VALUE, 1); f2 = Fraction.ONE; f = f1.subtract(f2); @@ -508,7 +508,7 @@ public class FractionTest extends TestCase { f = f1.subtract(f2); fail("expecting ArithmeticException"); //should overflow } catch (ArithmeticException ex) {} - + // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(1,5); @@ -516,19 +516,19 @@ public class FractionTest extends TestCase { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} - + try { f= new Fraction(Integer.MIN_VALUE, 1); f = f.subtract(Fraction.ONE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} - + try { f= new Fraction(Integer.MAX_VALUE, 1); f = f.subtract(Fraction.ONE.negate()); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} - + f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { @@ -536,7 +536,7 @@ public class FractionTest extends TestCase { fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } - + public void testEqualsAndHashCode() { Fraction zero = new Fraction(0,1); Fraction nullFraction = null; @@ -549,7 +549,7 @@ public class FractionTest extends TestCase { Fraction one = new Fraction(1,1); assertFalse((one.equals(zero) ||zero.equals(one))); } - + public void testGetReducedFraction() { Fraction threeFourths = new Fraction(3, 4); assertTrue(threeFourths.equals(Fraction.getReducedFraction(6, 8))); diff --git a/src/test/java/org/apache/commons/math/genetics/BinaryChromosomeTest.java b/src/test/java/org/apache/commons/math/genetics/BinaryChromosomeTest.java index 4867a16bb..e084b2cb9 100644 --- a/src/test/java/org/apache/commons/math/genetics/BinaryChromosomeTest.java +++ b/src/test/java/org/apache/commons/math/genetics/BinaryChromosomeTest.java @@ -23,31 +23,31 @@ import static org.junit.Assert.fail; import org.junit.Test; public class BinaryChromosomeTest { - + @Test - public void testInvalidConstructor() { + public void testInvalidConstructor() { Integer[][] reprs = new Integer[][] { new Integer[] {0,1,0,1,2}, new Integer[] {0,1,0,1,-1} }; - + for (Integer[] repr : reprs) { try { new DummyBinaryChromosome(repr); fail("Exception not caught"); } catch (IllegalArgumentException e) { - + } } } - + @Test public void testRandomConstructor() { for (int i=0; i<20; i++) { new DummyBinaryChromosome(BinaryChromosome.randomBinaryRepresentation(10)); } } - + @Test public void testIsSame() { Chromosome c1 = new DummyBinaryChromosome(new Integer[] {0,1,0,1,0,1}); @@ -56,7 +56,7 @@ public class BinaryChromosomeTest { Chromosome c4 = new DummyBinaryChromosome(new Integer[] {1,1,0,1,0,1}); Chromosome c5 = new DummyBinaryChromosome(new Integer[] {0,1,0,1,0,0}); Chromosome c6 = new DummyBinaryChromosome(new Integer[] {0,1,0,1,0,1}); - + assertFalse(c1.isSame(c2)); assertFalse(c1.isSame(c3)); assertFalse(c1.isSame(c4)); diff --git a/src/test/java/org/apache/commons/math/genetics/BinaryMutationTest.java b/src/test/java/org/apache/commons/math/genetics/BinaryMutationTest.java index 4d1a99580..3483db4aa 100644 --- a/src/test/java/org/apache/commons/math/genetics/BinaryMutationTest.java +++ b/src/test/java/org/apache/commons/math/genetics/BinaryMutationTest.java @@ -25,12 +25,12 @@ public class BinaryMutationTest { @Test public void testMutate() { BinaryMutation mutation = new BinaryMutation(); - + // stochastic testing :) for (int i=0; i<20; i++) { - DummyBinaryChromosome original = new DummyBinaryChromosome(BinaryChromosome.randomBinaryRepresentation(10)); + DummyBinaryChromosome original = new DummyBinaryChromosome(BinaryChromosome.randomBinaryRepresentation(10)); DummyBinaryChromosome mutated = (DummyBinaryChromosome) mutation.mutate(original); - + // one gene should be different int numDifferent = 0; for (int j=0; j 0); assertEquals(0,c3.compareTo(c2)); assertEquals(0,c2.compareTo(c3)); } - + private abstract static class DummyChromosome extends Chromosome { private final int repr; @@ -60,7 +60,7 @@ public class ChromosomeTest { return ((DummyChromosome) another).repr == repr; } } - + @Test public void testFindSameChromosome() { Chromosome c1 = new DummyChromosome(1) { @@ -88,7 +88,7 @@ public class ChromosomeTest { return 15; } }; - + List popChr = new ArrayList(); popChr.add(c1); popChr.add(c2); @@ -99,10 +99,10 @@ public class ChromosomeTest { return null; } }; - + assertNull(c5.findSameChromosome(pop)); assertEquals(c1, c4.findSameChromosome(pop)); - + c4.searchForFitnessUpdate(pop); assertEquals(1, c4.getFitness(),0); } diff --git a/src/test/java/org/apache/commons/math/genetics/DummyBinaryChromosome.java b/src/test/java/org/apache/commons/math/genetics/DummyBinaryChromosome.java index 94194de58..f76cc57ce 100644 --- a/src/test/java/org/apache/commons/math/genetics/DummyBinaryChromosome.java +++ b/src/test/java/org/apache/commons/math/genetics/DummyBinaryChromosome.java @@ -26,7 +26,7 @@ public class DummyBinaryChromosome extends BinaryChromosome { public DummyBinaryChromosome(List representation) { super(representation); } - + public DummyBinaryChromosome(Integer[] representation) { super(representation); } diff --git a/src/test/java/org/apache/commons/math/genetics/DummyRandomKey.java b/src/test/java/org/apache/commons/math/genetics/DummyRandomKey.java index a37961a20..4e688aabe 100644 --- a/src/test/java/org/apache/commons/math/genetics/DummyRandomKey.java +++ b/src/test/java/org/apache/commons/math/genetics/DummyRandomKey.java @@ -26,7 +26,7 @@ public class DummyRandomKey extends RandomKey { public DummyRandomKey(List representation) { super(representation); } - + public DummyRandomKey(Double[] representation) { super(representation); } @@ -40,5 +40,5 @@ public class DummyRandomKey extends RandomKey { // unimportant return 0; } - + } diff --git a/src/test/java/org/apache/commons/math/genetics/ElitisticListPopulationTest.java b/src/test/java/org/apache/commons/math/genetics/ElitisticListPopulationTest.java index d779f7814..fad194588 100644 --- a/src/test/java/org/apache/commons/math/genetics/ElitisticListPopulationTest.java +++ b/src/test/java/org/apache/commons/math/genetics/ElitisticListPopulationTest.java @@ -21,31 +21,31 @@ import static org.junit.Assert.*; import org.junit.Test; public class ElitisticListPopulationTest { - + private static int counter = 0; @Test public void testNextGeneration() { ElitisticListPopulation pop = new ElitisticListPopulation(100, 0.203); - + for (int i=0; i popList = new LinkedList(); - + for (int i=0; i representation) { super(representation); - } + } @Override public double fitness() { diff --git a/src/test/java/org/apache/commons/math/genetics/FixedGenerationCountTest.java b/src/test/java/org/apache/commons/math/genetics/FixedGenerationCountTest.java index 38ac51cac..66cbe4c44 100644 --- a/src/test/java/org/apache/commons/math/genetics/FixedGenerationCountTest.java +++ b/src/test/java/org/apache/commons/math/genetics/FixedGenerationCountTest.java @@ -27,7 +27,7 @@ public class FixedGenerationCountTest { @Test public void testIsSatisfied() { FixedGenerationCount fgc = new FixedGenerationCount(20); - + int cnt = 0; Population pop = new Population() { public void addChromosome(Chromosome chromosome) { @@ -54,7 +54,7 @@ public class FixedGenerationCountTest { return null; } }; - + while (!fgc.isSatisfied(pop)) cnt++; assertEquals(20, cnt); diff --git a/src/test/java/org/apache/commons/math/genetics/GeneticAlgorithmTestBinary.java b/src/test/java/org/apache/commons/math/genetics/GeneticAlgorithmTestBinary.java index 14cacd8f2..32af2c477 100644 --- a/src/test/java/org/apache/commons/math/genetics/GeneticAlgorithmTestBinary.java +++ b/src/test/java/org/apache/commons/math/genetics/GeneticAlgorithmTestBinary.java @@ -26,10 +26,10 @@ import org.junit.Test; * This is also an example of usage. */ public class GeneticAlgorithmTestBinary { - + // parameters for the GA - private static final int DIMENSION = 50; - private static final int POPULATION_SIZE = 50; + private static final int DIMENSION = 50; + private static final int POPULATION_SIZE = 50; private static final int NUM_GENERATIONS = 50; private static final double ELITISM_RATE = 0.2; private static final double CROSSOVER_RATE = 1; @@ -39,7 +39,7 @@ public class GeneticAlgorithmTestBinary { @Test public void test() { // to test a stochastic algorithm is hard, so this will rather be an usage example - + // initialize a new genetic algorithm GeneticAlgorithm ga = new GeneticAlgorithm( new OnePointCrossover(), @@ -48,49 +48,49 @@ public class GeneticAlgorithmTestBinary { MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY) ); - + // initial population Population initial = randomPopulation(); // stopping conditions StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS); - + // best initial chromosome Chromosome bestInitial = initial.getFittestChromosome(); - + // run the algorithm Population finalPopulation = ga.evolve(initial, stopCond); - + // best chromosome from the final population Chromosome bestFinal = finalPopulation.getFittestChromosome(); - + // the only thing we can test is whether the final solution is not worse than the initial one // however, for some implementations of GA, this need not be true :) - + assertTrue(bestFinal.compareTo(bestInitial) > 0); - + //System.out.println(bestInitial); //System.out.println(bestFinal); } - - - - + + + + /** * Initializes a random population. */ private static ElitisticListPopulation randomPopulation() { List popList = new LinkedList(); - + for (int i=0; i sequence = new ArrayList(); static { @@ -51,7 +51,7 @@ public class GeneticAlgorithmTestPermutations { @Test public void test() { // to test a stochastic algorithm is hard, so this will rather be an usage example - + // initialize a new genetic algorithm GeneticAlgorithm ga = new GeneticAlgorithm( new OnePointCrossover(), @@ -60,31 +60,31 @@ public class GeneticAlgorithmTestPermutations { MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY) ); - + // initial population Population initial = randomPopulation(); // stopping conditions StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS); - + // best initial chromosome Chromosome bestInitial = initial.getFittestChromosome(); - + // run the algorithm Population finalPopulation = ga.evolve(initial, stopCond); - + // best chromosome from the final population Chromosome bestFinal = finalPopulation.getFittestChromosome(); - + // the only thing we can test is whether the final solution is not worse than the initial one // however, for some implementations of GA, this need not be true :) - + assertTrue(bestFinal.compareTo(bestInitial) > 0); - + //System.out.println(bestInitial); //System.out.println(bestFinal); } - - + + /** * Initializes a random population */ @@ -96,10 +96,10 @@ public class GeneticAlgorithmTestPermutations { } return new ElitisticListPopulation(popList, popList.size(), ELITISM_RATE); } - + /** * Chromosomes representing a permutation of (0,1,2,...,DIMENSION-1). - * + * * The goal is to sort the sequence. */ private static class MinPermutations extends RandomKey { @@ -120,7 +120,7 @@ public class GeneticAlgorithmTestPermutations { } // the most fitted chromosome is the one with minimal error // therefore we must return negative value - return -res; + return -res; } @Override diff --git a/src/test/java/org/apache/commons/math/genetics/ListPopulationTest.java b/src/test/java/org/apache/commons/math/genetics/ListPopulationTest.java index e56c42dd0..f43ef95cb 100644 --- a/src/test/java/org/apache/commons/math/genetics/ListPopulationTest.java +++ b/src/test/java/org/apache/commons/math/genetics/ListPopulationTest.java @@ -27,26 +27,26 @@ public class ListPopulationTest { @Test public void testGetFittestChromosome() { Chromosome c1 = new Chromosome() { - public double fitness() { + public double fitness() { return 0; } }; Chromosome c2 = new Chromosome() { - public double fitness() { + public double fitness() { return 10; } }; Chromosome c3 = new Chromosome() { - public double fitness() { + public double fitness() { return 15; } }; - + ArrayList chromosomes = new ArrayList (); chromosomes.add(c1); chromosomes.add(c2); chromosomes.add(c3); - + ListPopulation population = new ListPopulation(chromosomes,10) { public Population nextGeneration() { @@ -54,7 +54,7 @@ public class ListPopulationTest { return null; } }; - + assertEquals(c3, population.getFittestChromosome()); } diff --git a/src/test/java/org/apache/commons/math/genetics/OnePointCrossoverTest.java b/src/test/java/org/apache/commons/math/genetics/OnePointCrossoverTest.java index 7d5a1edc2..a332498fc 100644 --- a/src/test/java/org/apache/commons/math/genetics/OnePointCrossoverTest.java +++ b/src/test/java/org/apache/commons/math/genetics/OnePointCrossoverTest.java @@ -25,22 +25,22 @@ public class OnePointCrossoverTest { public void testCrossover() { Integer[] p1 = new Integer[] {1,0,1,0,0,1,0,1,1}; Integer[] p2 = new Integer[] {0,1,1,0,1,0,1,1,1}; - + BinaryChromosome p1c = new DummyBinaryChromosome(p1); BinaryChromosome p2c = new DummyBinaryChromosome(p2); - + OnePointCrossover opc = new OnePointCrossover(); - + // how to test a stochastic method? for (int i=0; i<20; i++) { ChromosomePair pair = opc.crossover(p1c,p2c); - + Integer[] c1 = new Integer[p1.length]; Integer[] c2 = new Integer[p2.length]; - + c1 = ((BinaryChromosome) pair.getFirst()).getRepresentation().toArray(c1); c2 = ((BinaryChromosome) pair.getSecond()).getRepresentation().toArray(c2); - + // first and last values will be the same assertEquals((int) p1[0], (int) c1[0]); assertEquals((int) p2[0], (int) c2[0]); diff --git a/src/test/java/org/apache/commons/math/genetics/RandomKeyMutationTest.java b/src/test/java/org/apache/commons/math/genetics/RandomKeyMutationTest.java index aaa1ebecb..dc5bab510 100644 --- a/src/test/java/org/apache/commons/math/genetics/RandomKeyMutationTest.java +++ b/src/test/java/org/apache/commons/math/genetics/RandomKeyMutationTest.java @@ -30,7 +30,7 @@ public class RandomKeyMutationTest { DummyRandomKey origRk = new DummyRandomKey(RandomKey.randomPermutation(l)); Chromosome mutated = mutation.mutate(origRk); DummyRandomKey mutatedRk = (DummyRandomKey) mutated; - + int changes = 0; for (int j=0; j decoded = drk.decode(Arrays.asList(new String[] {"a", "b", "c", "d", "e"})); - + assertEquals("b", decoded.get(0)); assertEquals("e", decoded.get(1)); assertEquals("a", decoded.get(2)); @@ -75,7 +75,7 @@ public class RandomKeyTest { public void testIdentityPermutation() { DummyRandomKey drk = new DummyRandomKey(RandomKey.identityPermutation(5)); List decoded = drk.decode(Arrays.asList(new String[] {"a", "b", "c", "d", "e"})); - + assertEquals("a", decoded.get(0)); assertEquals("b", decoded.get(1)); assertEquals("c", decoded.get(2)); @@ -86,7 +86,7 @@ public class RandomKeyTest { @Test public void testComparatorPermutation() { List data = Arrays.asList(new String[] {"x", "b", "c", "z", "b"}); - + List permutation = RandomKey.comparatorPermutation(data, new Comparator() { public int compare(String o1, String o2) { return o1.compareTo(o2); @@ -101,7 +101,7 @@ public class RandomKeyTest { assertEquals("c", decodedData.get(2)); assertEquals("x", decodedData.get(3)); assertEquals("z", decodedData.get(4)); - + permutation = RandomKey.comparatorPermutation(data, new Comparator() { public int compare(String o1, String o2) { return o2.compareTo(o1); @@ -117,15 +117,15 @@ public class RandomKeyTest { assertEquals("b", decodedData.get(3)); assertEquals("b", decodedData.get(4)); } - + @Test public void testInducedPermutation() { List origData = Arrays.asList(new String[] {"a", "b", "c", "d", "d"}); List permutedData = Arrays.asList(new String[] {"d", "b", "c", "a", "d"}); - + DummyRandomKey drk = new DummyRandomKey(RandomKey.inducedPermutation(origData, permutedData)); List decoded = drk.decode(origData); - + assertEquals("d", decoded.get(0)); assertEquals("b", decoded.get(1)); assertEquals("c", decoded.get(2)); @@ -160,5 +160,5 @@ public class RandomKeyTest { assertEquals("b", decodedData.get(1)); assertEquals("c", decodedData.get(2)); } - + } diff --git a/src/test/java/org/apache/commons/math/genetics/TournamentSelectionTest.java b/src/test/java/org/apache/commons/math/genetics/TournamentSelectionTest.java index 8c39c4a32..d6b3f7a2a 100644 --- a/src/test/java/org/apache/commons/math/genetics/TournamentSelectionTest.java +++ b/src/test/java/org/apache/commons/math/genetics/TournamentSelectionTest.java @@ -20,14 +20,14 @@ import static org.junit.Assert.*; import org.junit.Test; public class TournamentSelectionTest { - + private static int counter = 0; @Test public void testSelect() { TournamentSelection ts = new TournamentSelection(2); ElitisticListPopulation pop = new ElitisticListPopulation(100, 0.203); - + for (int i=0; i 0); } } - + private static class DummyChromosome extends Chromosome { private final int fitness; - + public DummyChromosome() { this.fitness = counter; counter++; } - - public double fitness() { + + public double fitness() { return this.fitness; } } diff --git a/src/test/java/org/apache/commons/math/geometry/FrenchVector3DFormatTest.java b/src/test/java/org/apache/commons/math/geometry/FrenchVector3DFormatTest.java index 61f94e347..c70b1d9cc 100644 --- a/src/test/java/org/apache/commons/math/geometry/FrenchVector3DFormatTest.java +++ b/src/test/java/org/apache/commons/math/geometry/FrenchVector3DFormatTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/test/java/org/apache/commons/math/geometry/Vector3DFormatAbstractTest.java b/src/test/java/org/apache/commons/math/geometry/Vector3DFormatAbstractTest.java index 4edfc049c..ff3218771 100644 --- a/src/test/java/org/apache/commons/math/geometry/Vector3DFormatAbstractTest.java +++ b/src/test/java/org/apache/commons/math/geometry/Vector3DFormatAbstractTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,7 +27,7 @@ import junit.framework.TestCase; import org.apache.commons.math.util.CompositeFormat; public abstract class Vector3DFormatAbstractTest extends TestCase { - + Vector3DFormat vector3DFormat = null; Vector3DFormat vector3DFormatSquare = null; @@ -42,11 +42,11 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { nf.setMaximumFractionDigits(2); vector3DFormatSquare = new Vector3DFormat("[", "]", " : ", nf); } - + public void testSimpleNoDecimals() { Vector3D c = new Vector3D(1, 1, 1); String expected = "{1; 1; 1}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } @@ -57,7 +57,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "23; 1" + getDecimalCharacter() + "43; 1" + getDecimalCharacter() + "63}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } @@ -68,7 +68,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "23; 1" + getDecimalCharacter() + "43; 1" + getDecimalCharacter() + "63}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } @@ -79,7 +79,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "23; 1" + getDecimalCharacter() + "43; 1" + getDecimalCharacter() + "63}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } @@ -90,7 +90,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "23; -1" + getDecimalCharacter() + "43; 1" + getDecimalCharacter() + "63}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } @@ -101,51 +101,51 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "23; 1" + getDecimalCharacter() + "43; -1" + getDecimalCharacter() + "63}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } public void testNonDefaultSetting() { Vector3D c = new Vector3D(1, 1, 1); String expected = "[1 : 1 : 1]"; - String actual = vector3DFormatSquare.format(c); + String actual = vector3DFormatSquare.format(c); assertEquals(expected, actual); } - + public void testStaticFormatVector3D() { Locale defaultLocal = Locale.getDefault(); Locale.setDefault(getLocale()); - + Vector3D c = new Vector3D(232.222, -342.33, 432.444); String expected = "{232" + getDecimalCharacter() + "22; -342" + getDecimalCharacter() + "33; 432" + getDecimalCharacter() + "44}"; - String actual = Vector3DFormat.formatVector3D(c); + String actual = Vector3DFormat.formatVector3D(c); assertEquals(expected, actual); - + Locale.setDefault(defaultLocal); } public void testNan() { Vector3D c = Vector3D.NaN; String expected = "{(NaN); (NaN); (NaN)}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } public void testPositiveInfinity() { Vector3D c = Vector3D.POSITIVE_INFINITY; String expected = "{(Infinity); (Infinity); (Infinity)}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } public void tesNegativeInfinity() { Vector3D c = Vector3D.NEGATIVE_INFINITY; String expected = "{(-Infinity); (-Infinity); (-Infinity)}"; - String actual = vector3DFormat.format(c); + String actual = vector3DFormat.format(c); assertEquals(expected, actual); } @@ -153,7 +153,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { String source = "{1; 1; 1}"; Vector3D expected = new Vector3D(1, 1, 1); try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -180,7 +180,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "63}"; Vector3D expected = new Vector3D(1.23, 1.43, 1.63); try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -195,7 +195,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "6333}"; Vector3D expected = new Vector3D(1.2323, 1.4343, 1.6333); try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -210,7 +210,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "6333}"; Vector3D expected = new Vector3D(-1.2323, 1.4343, 1.6333); try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -225,7 +225,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "6333}"; Vector3D expected = new Vector3D(1.2323, -1.4343, 1.6333); try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -240,7 +240,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "6333}"; Vector3D expected = new Vector3D(1.2323, 1.4343, -1.6333); try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -255,7 +255,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "6333}"; Vector3D expected = new Vector3D(-1.2323, -1.4343, -1.6333); try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -270,7 +270,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "6333}"; Vector3D expected = new Vector3D(0.0, -1.4343, 1.6333); try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -285,17 +285,17 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { "6333]"; Vector3D expected = new Vector3D(1.2323, 1.4343, 1.6333); try { - Vector3D actual = (Vector3D) vector3DFormatSquare.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormatSquare.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); } } - + public void testParseNan() { String source = "{(NaN); (NaN); (NaN)}"; try { - Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D) vector3DFormat.parseObject(source); assertEquals(Vector3D.NaN, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -305,7 +305,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { public void testParsePositiveInfinity() { String source = "{(Infinity); (Infinity); (Infinity)}"; try { - Vector3D actual = (Vector3D)vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D)vector3DFormat.parseObject(source); assertEquals(Vector3D.POSITIVE_INFINITY, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -315,7 +315,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { public void testParseNegativeInfinity() { String source = "{(-Infinity); (-Infinity); (-Infinity)}"; try { - Vector3D actual = (Vector3D)vector3DFormat.parseObject(source); + Vector3D actual = (Vector3D)vector3DFormat.parseObject(source); assertEquals(Vector3D.NEGATIVE_INFINITY, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -328,7 +328,7 @@ public abstract class Vector3DFormatAbstractTest extends TestCase { assertNotNull(cf); assertEquals(nf, cf.getFormat()); } - + public void testFormatObject() { try { CompositeFormat cf = new Vector3DFormat(); diff --git a/src/test/java/org/apache/commons/math/geometry/Vector3DFormatTest.java b/src/test/java/org/apache/commons/math/geometry/Vector3DFormatTest.java index 716edadef..ca3f28797 100644 --- a/src/test/java/org/apache/commons/math/geometry/Vector3DFormatTest.java +++ b/src/test/java/org/apache/commons/math/geometry/Vector3DFormatTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/test/java/org/apache/commons/math/geometry/Vector3DTest.java b/src/test/java/org/apache/commons/math/geometry/Vector3DTest.java index 8f697cbf7..22791118d 100644 --- a/src/test/java/org/apache/commons/math/geometry/Vector3DTest.java +++ b/src/test/java/org/apache/commons/math/geometry/Vector3DTest.java @@ -52,7 +52,7 @@ public class Vector3DTest assertTrue(Math.abs(v.getY() - 2) < 1.0e-12); assertTrue(Math.abs(v.getZ() - 3) < 1.0e-12); } - + public void testNorm1() { assertEquals(0.0, Vector3D.ZERO.getNorm1()); assertEquals(6.0, new Vector3D(1, -2, 3).getNorm1(), 0); @@ -203,13 +203,13 @@ public class Vector3DTest } public void testAngle() { - assertEquals(0.22572612855273393616, + assertEquals(0.22572612855273393616, Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(4, 5, 6)), 1.0e-12); - assertEquals(7.98595620686106654517199e-8, + assertEquals(7.98595620686106654517199e-8, Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(2, 4, 6.000001)), 1.0e-12); - assertEquals(3.14159257373023116985197793156, + assertEquals(3.14159257373023116985197793156, Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(-2, -4, -6.000001)), 1.0e-12); try { @@ -227,7 +227,7 @@ public class Vector3DTest assertEquals(y, v.getY(), 1.0e-12); assertEquals(z, v.getZ(), 1.0e-12); } - + public static Test suite() { return new TestSuite(Vector3DTest.class); } diff --git a/src/test/java/org/apache/commons/math/linear/Array2DRowRealMatrixTest.java b/src/test/java/org/apache/commons/math/linear/Array2DRowRealMatrixTest.java index c0195bf32..1eccf7cfa 100644 --- a/src/test/java/org/apache/commons/math/linear/Array2DRowRealMatrixTest.java +++ b/src/test/java/org/apache/commons/math/linear/Array2DRowRealMatrixTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,45 +29,45 @@ import org.apache.commons.math.TestUtils; */ public final class Array2DRowRealMatrixTest extends TestCase { - + // 3 x 3 identity matrix protected double[][] id = { {1d,0d,0d}, {0d,1d,0d}, {0d,0d,1d} }; - + // Test data for group operations protected double[][] testData = { {1d,2d,3d}, {2d,5d,3d}, {1d,0d,8d} }; protected double[][] testDataLU = {{2d, 5d, 3d}, {.5d, -2.5d, 6.5d}, {0.5d, 0.2d, .2d}}; protected double[][] testDataPlus2 = { {3d,4d,5d}, {4d,7d,5d}, {3d,2d,10d} }; - protected double[][] testDataMinus = { {-1d,-2d,-3d}, {-2d,-5d,-3d}, + protected double[][] testDataMinus = { {-1d,-2d,-3d}, {-2d,-5d,-3d}, {-1d,0d,-8d} }; protected double[] testDataRow1 = {1d,2d,3d}; protected double[] testDataCol3 = {3d,3d,8d}; - protected double[][] testDataInv = + protected double[][] testDataInv = { {-40d,16d,9d}, {13d,-5d,-3d}, {5d,-2d,-1d} }; protected double[] preMultTest = {8,12,33}; protected double[][] testData2 ={ {1d,2d,3d}, {2d,5d,3d}}; protected double[][] testData2T = { {1d,2d}, {2d,5d}, {3d,3d}}; - protected double[][] testDataPlusInv = + protected double[][] testDataPlusInv = { {-39d,18d,12d}, {15d,0d,0d}, {6d,-2d,7d} }; - + // lu decomposition tests protected double[][] luData = { {2d,3d,3d}, {0d,5d,7d}, {6d,9d,8d} }; protected double[][] luDataLUDecomposition = { {6d,9d,8d}, {0d,5d,7d}, {0.33333333333333,0d,0.33333333333333} }; - + // singular matrices protected double[][] singular = { {2d,3d}, {2d,3d} }; protected double[][] bigSingular = {{1d,2d,3d,4d}, {2d,5d,3d,4d}, {7d,3d,256d,1930d}, {3d,7d,6d,8d}}; // 4th row = 1st + 2nd protected double[][] detData = { {1d,2d,3d}, {4d,5d,6d}, {7d,8d,10d} }; protected double[][] detData2 = { {1d, 3d}, {2d, 4d}}; - + // vectors protected double[] testVector = {1,2,3}; protected double[] testVector2 = {1,2,3,4}; - + // submatrix accessor tests protected double[][] subTestData = {{1, 2, 3, 4}, {1.5, 2.5, 3.5, 4.5}, - {2, 4, 6, 8}, {4, 5, 6, 7}}; + {2, 4, 6, 8}, {4, 5, 6, 7}}; // array selections protected double[][] subRows02Cols13 = { {2, 4}, {4, 8}}; protected double[][] subRows03Cols12 = { {2, 3}, {5, 6}}; @@ -85,21 +85,21 @@ public final class Array2DRowRealMatrixTest extends TestCase { // column matrices protected double[][] subColumn1 = {{2}, {2.5}, {4}, {5}}; protected double[][] subColumn3 = {{4}, {4.5}, {8}, {7}}; - + // tolerances protected double entryTolerance = 10E-16; protected double normTolerance = 10E-14; - + public Array2DRowRealMatrixTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(Array2DRowRealMatrixTest.class); suite.setName("Array2DRowRealMatrix Tests"); return suite; } - + /** test dimensions */ public void testDimensions() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); @@ -110,8 +110,8 @@ public final class Array2DRowRealMatrixTest extends TestCase { assertEquals("testData2 row dimension",m2.getRowDimension(),2); assertEquals("testData2 column dimension",m2.getColumnDimension(),3); assertTrue("testData2 is not square",!m2.isSquare()); - } - + } + /** test copy functions */ public void testCopyFunctions() { Array2DRowRealMatrix m1 = new Array2DRowRealMatrix(testData); @@ -120,8 +120,8 @@ public final class Array2DRowRealMatrixTest extends TestCase { Array2DRowRealMatrix m3 = new Array2DRowRealMatrix(testData); Array2DRowRealMatrix m4 = new Array2DRowRealMatrix(m3.getData(), false); assertEquals(m4,m3); - } - + } + /** test add */ public void testAdd() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); @@ -134,9 +134,9 @@ public final class Array2DRowRealMatrixTest extends TestCase { testDataPlusInv[row][col],sumEntries[row][col], entryTolerance); } - } + } } - + /** test add failure */ public void testAddFail() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); @@ -148,7 +148,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { // ignored } } - + /** test norm */ public void testNorm() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); @@ -156,7 +156,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { assertEquals("testData norm",14d,m.getNorm(),entryTolerance); assertEquals("testData2 norm",7d,m2.getNorm(),entryTolerance); } - + /** test Frobenius norm */ public void testFrobeniusNorm() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); @@ -164,21 +164,21 @@ public final class Array2DRowRealMatrixTest extends TestCase { assertEquals("testData Frobenius norm", Math.sqrt(117.0), m.getFrobeniusNorm(), entryTolerance); assertEquals("testData2 Frobenius norm", Math.sqrt(52.0), m2.getFrobeniusNorm(), entryTolerance); } - + /** test m-n = m + -n */ public void testPlusMinus() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); Array2DRowRealMatrix m2 = new Array2DRowRealMatrix(testDataInv); TestUtils.assertEquals("m-n = m + -n",m.subtract(m2), - m2.scalarMultiply(-1d).add(m),entryTolerance); + m2.scalarMultiply(-1d).add(m),entryTolerance); try { m.subtract(new Array2DRowRealMatrix(testData2)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + /** test multiply */ public void testMultiply() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); @@ -194,28 +194,28 @@ public final class Array2DRowRealMatrixTest extends TestCase { TestUtils.assertEquals("identity multiply",identity.multiply(mInv), mInv,entryTolerance); TestUtils.assertEquals("identity multiply",m2.multiply(identity), - m2,entryTolerance); + m2,entryTolerance); try { m.multiply(new Array2DRowRealMatrix(bigSingular)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } - } - + } + } + //Additional Test for Array2DRowRealMatrixTest.testMultiply private double[][] d3 = new double[][] {{1,2,3,4},{5,6,7,8}}; private double[][] d4 = new double[][] {{1},{2},{3},{4}}; private double[][] d5 = new double[][] {{30},{70}}; - - public void testMultiply2() { - RealMatrix m3 = new Array2DRowRealMatrix(d3); + + public void testMultiply2() { + RealMatrix m3 = new Array2DRowRealMatrix(d3); RealMatrix m4 = new Array2DRowRealMatrix(d4); RealMatrix m5 = new Array2DRowRealMatrix(d5); TestUtils.assertEquals("m3*m4=m5", m3.multiply(m4), m5, entryTolerance); - } - + } + /** test trace */ public void testTrace() { RealMatrix m = new Array2DRowRealMatrix(id); @@ -226,16 +226,16 @@ public final class Array2DRowRealMatrixTest extends TestCase { fail("Expecting NonSquareMatrixException"); } catch (NonSquareMatrixException ex) { // ignored - } + } } - + /** test sclarAdd */ public void testScalarAdd() { RealMatrix m = new Array2DRowRealMatrix(testData); TestUtils.assertEquals("scalar add",new Array2DRowRealMatrix(testDataPlus2), m.scalarAdd(2d),entryTolerance); } - + /** test operate */ public void testOperate() { RealMatrix m = new Array2DRowRealMatrix(id); @@ -249,7 +249,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } /** test issue MATH-209 */ @@ -263,10 +263,10 @@ public final class Array2DRowRealMatrixTest extends TestCase { assertEquals( 7.0, b[1], 1.0e-12); assertEquals(11.0, b[2], 1.0e-12); } - + /** test transpose */ public void testTranspose() { - RealMatrix m = new Array2DRowRealMatrix(testData); + RealMatrix m = new Array2DRowRealMatrix(testData); RealMatrix mIT = new LUDecompositionImpl(m).getSolver().getInverse().transpose(); RealMatrix mTI = new LUDecompositionImpl(m.transpose()).getSolver().getInverse(); TestUtils.assertEquals("inverse-transpose", mIT, mTI, normTolerance); @@ -274,7 +274,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { RealMatrix mt = new Array2DRowRealMatrix(testData2T); TestUtils.assertEquals("transpose",mt,m.transpose(),normTolerance); } - + /** test preMultiply by vector */ public void testPremultiplyVector() { RealMatrix m = new Array2DRowRealMatrix(testData); @@ -290,13 +290,13 @@ public final class Array2DRowRealMatrixTest extends TestCase { // ignored } } - + public void testPremultiply() { - RealMatrix m3 = new Array2DRowRealMatrix(d3); + RealMatrix m3 = new Array2DRowRealMatrix(d3); RealMatrix m4 = new Array2DRowRealMatrix(d4); RealMatrix m5 = new Array2DRowRealMatrix(d5); TestUtils.assertEquals("m3*m4=m5", m4.preMultiply(m3), m5, entryTolerance); - + Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); Array2DRowRealMatrix mInv = new Array2DRowRealMatrix(testDataInv); Array2DRowRealMatrix identity = new Array2DRowRealMatrix(id); @@ -313,9 +313,9 @@ public final class Array2DRowRealMatrixTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + public void testGetVectors() { RealMatrix m = new Array2DRowRealMatrix(testData); TestUtils.assertEquals("get row",m.getRow(0),testDataRow1,entryTolerance); @@ -333,7 +333,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { // ignored } } - + public void testGetEntry() { RealMatrix m = new Array2DRowRealMatrix(testData); assertEquals("get entry",m.getEntry(0,1),2d,entryTolerance); @@ -344,7 +344,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { // expected } } - + /** test examples in user guide */ public void testExamples() { // Create a real matrix with two rows and three columns @@ -358,10 +358,10 @@ public final class Array2DRowRealMatrixTest extends TestCase { assertEquals(2, p.getRowDimension()); assertEquals(2, p.getColumnDimension()); // Invert p - RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse(); + RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse(); assertEquals(2, pInverse.getRowDimension()); assertEquals(2, pInverse.getColumnDimension()); - + // Solve example double[][] coefficientsData = {{2, 3, -2}, {-1, 7, 6}, {4, -3, -5}}; RealMatrix coefficients = new Array2DRowRealMatrix(coefficientsData); @@ -369,22 +369,22 @@ public final class Array2DRowRealMatrixTest extends TestCase { double[] solution = new LUDecompositionImpl(coefficients).getSolver().solve(constants); assertEquals(2 * solution[0] + 3 * solution[1] -2 * solution[2], constants[0], 1E-12); assertEquals(-1 * solution[0] + 7 * solution[1] + 6 * solution[2], constants[1], 1E-12); - assertEquals(4 * solution[0] - 3 * solution[1] -5 * solution[2], constants[2], 1E-12); - + assertEquals(4 * solution[0] - 3 * solution[1] -5 * solution[2], constants[2], 1E-12); + } - + // test submatrix accessors public void testGetSubMatrix() { RealMatrix m = new Array2DRowRealMatrix(subTestData); checkGetSubMatrix(m, subRows23Cols00, 2 , 3 , 0, 0, false); checkGetSubMatrix(m, subRows00Cols33, 0 , 0 , 3, 3, false); - checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3, false); - checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }, false); - checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }, false); - checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }, false); - checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }, false); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); + checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3, false); + checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }, false); + checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }, false); + checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }, false); + checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }, false); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); checkGetSubMatrix(m, null, 1, 0, 2, 4, true); checkGetSubMatrix(m, null, -1, 1, 2, 2, true); checkGetSubMatrix(m, null, 1, 0, 2, 2, true); @@ -408,7 +408,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { } } } - + private void checkGetSubMatrix(RealMatrix m, double[][] reference, int[] selectedRows, int[] selectedColumns, boolean mustFail) { @@ -429,14 +429,14 @@ public final class Array2DRowRealMatrixTest extends TestCase { RealMatrix m = new Array2DRowRealMatrix(subTestData); checkCopy(m, subRows23Cols00, 2 , 3 , 0, 0, false); checkCopy(m, subRows00Cols33, 0 , 0 , 3, 3, false); - checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3, false); - checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }, false); - checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }, false); - checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }, false); - checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }, false); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); - + checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3, false); + checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }, false); + checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }, false); + checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }, false); + checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }, false); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); + checkCopy(m, null, 1, 0, 2, 4, true); checkCopy(m, null, -1, 1, 2, 2, true); checkCopy(m, null, 1, 0, 2, 2, true); @@ -463,7 +463,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { } } } - + private void checkCopy(RealMatrix m, double[][] reference, int[] selectedRows, int[] selectedColumns, boolean mustFail) { @@ -487,9 +487,9 @@ public final class Array2DRowRealMatrixTest extends TestCase { RealMatrix m = new Array2DRowRealMatrix(subTestData); RealMatrix mRow0 = new Array2DRowRealMatrix(subRow0); RealMatrix mRow3 = new Array2DRowRealMatrix(subRow3); - assertEquals("Row0", mRow0, + assertEquals("Row0", mRow0, m.getRowMatrix(0)); - assertEquals("Row3", mRow3, + assertEquals("Row3", mRow3, m.getRowMatrix(3)); try { m.getRowMatrix(-1); @@ -504,7 +504,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { // expected } } - + public void testSetRowMatrix() { RealMatrix m = new Array2DRowRealMatrix(subTestData); RealMatrix mRow3 = new Array2DRowRealMatrix(subRow3); @@ -524,14 +524,14 @@ public final class Array2DRowRealMatrixTest extends TestCase { // expected } } - + public void testGetColumnMatrix() { RealMatrix m = new Array2DRowRealMatrix(subTestData); RealMatrix mColumn1 = new Array2DRowRealMatrix(subColumn1); RealMatrix mColumn3 = new Array2DRowRealMatrix(subColumn3); - assertEquals("Column1", mColumn1, + assertEquals("Column1", mColumn1, m.getColumnMatrix(1)); - assertEquals("Column3", mColumn3, + assertEquals("Column3", mColumn3, m.getColumnMatrix(3)); try { m.getColumnMatrix(-1); @@ -606,7 +606,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { // expected } } - + public void testGetColumnVector() { RealMatrix m = new Array2DRowRealMatrix(subTestData); RealVector mColumn1 = columnToVector(subColumn1); @@ -691,7 +691,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { // expected } } - + public void testGetColumn() { RealMatrix m = new Array2DRowRealMatrix(subTestData); double[] mColumn1 = columnToArray(subColumn1); @@ -743,10 +743,10 @@ public final class Array2DRowRealMatrixTest extends TestCase { private void checkArrays(double[] expected, double[] actual) { assertEquals(expected.length, actual.length); for (int i = 0; i < expected.length; ++i) { - assertEquals(expected[i], actual[i]); + assertEquals(expected[i], actual[i]); } } - + public void testEqualsAndHashCode() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); Array2DRowRealMatrix m1 = (Array2DRowRealMatrix) m.copy(); @@ -757,9 +757,9 @@ public final class Array2DRowRealMatrixTest extends TestCase { assertEquals(m, m1); assertFalse(m.equals(null)); assertFalse(m.equals(mt)); - assertFalse(m.equals(new Array2DRowRealMatrix(bigSingular))); + assertFalse(m.equals(new Array2DRowRealMatrix(bigSingular))); } - + public void testToString() { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); assertEquals("Array2DRowRealMatrix{{1.0,2.0,3.0},{2.0,5.0,3.0},{1.0,0.0,8.0}}", @@ -768,45 +768,45 @@ public final class Array2DRowRealMatrixTest extends TestCase { assertEquals("Array2DRowRealMatrix{}", m.toString()); } - + public void testSetSubMatrix() throws Exception { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); m.setSubMatrix(detData2,1,1); RealMatrix expected = MatrixUtils.createRealMatrix (new double[][] {{1.0,2.0,3.0},{2.0,1.0,3.0},{1.0,2.0,4.0}}); - assertEquals(expected, m); - + assertEquals(expected, m); + m.setSubMatrix(detData2,0,0); expected = MatrixUtils.createRealMatrix (new double[][] {{1.0,3.0,3.0},{2.0,4.0,3.0},{1.0,2.0,4.0}}); - assertEquals(expected, m); - - m.setSubMatrix(testDataPlus2,0,0); + assertEquals(expected, m); + + m.setSubMatrix(testDataPlus2,0,0); expected = MatrixUtils.createRealMatrix (new double[][] {{3.0,4.0,5.0},{4.0,7.0,5.0},{3.0,2.0,10.0}}); - assertEquals(expected, m); - + assertEquals(expected, m); + // dimension overflow - try { + try { m.setSubMatrix(testData,1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } // dimension underflow - try { + try { m.setSubMatrix(testData,-1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - try { + try { m.setSubMatrix(testData,1,-1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - + // null try { m.setSubMatrix(null,1,1); @@ -827,7 +827,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { } catch (IllegalStateException e) { // expected } - + // ragged try { m.setSubMatrix(new double[][] {{1}, {2, 3}}, 0, 0); @@ -835,7 +835,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + // empty try { m.setSubMatrix(new double[][] {{}}, 0, 0); @@ -843,7 +843,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + } public void testWalk() { @@ -862,11 +862,11 @@ public final class Array2DRowRealMatrixTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -882,11 +882,11 @@ public final class Array2DRowRealMatrixTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -902,11 +902,11 @@ public final class Array2DRowRealMatrixTest extends TestCase { m.walkInRowOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -922,11 +922,11 @@ public final class Array2DRowRealMatrixTest extends TestCase { m.walkInColumnOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -936,8 +936,8 @@ public final class Array2DRowRealMatrixTest extends TestCase { Array2DRowRealMatrix m = new Array2DRowRealMatrix(testData); assertEquals(m,TestUtils.serializeAndRecover(m)); } - - + + private static class SetVisitor extends DefaultRealMatrixChangingVisitor { @Override public double visit(int i, int j, double value) { @@ -958,14 +958,14 @@ public final class Array2DRowRealMatrixTest extends TestCase { } //--------------- -----------------Protected methods - + /** extracts the l and u matrices from compact lu representation */ - protected void splitLU(RealMatrix lu, double[][] lowerData, double[][] upperData) throws InvalidMatrixException { + protected void splitLU(RealMatrix lu, double[][] lowerData, double[][] upperData) throws InvalidMatrixException { if (!lu.isSquare() || lowerData.length != lowerData[0].length || upperData.length != upperData[0].length || lowerData.length != upperData.length || lowerData.length != lu.getRowDimension()) { throw new InvalidMatrixException("incorrect dimensions"); - } + } int n = lu.getRowDimension(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { @@ -978,11 +978,11 @@ public final class Array2DRowRealMatrixTest extends TestCase { } else { lowerData[i][j] = 0d; upperData[i][j] = lu.getEntry(i, j); - } + } } } } - + /** Returns the result of applying the given row permutation to the matrix */ protected RealMatrix permuteRows(RealMatrix matrix, int[] permutation) { if (!matrix.isSquare() || matrix.getRowDimension() != permutation.length) { @@ -998,7 +998,7 @@ public final class Array2DRowRealMatrixTest extends TestCase { } return new Array2DRowRealMatrix(out); } - + // /** Useful for debugging */ // private void dumpMatrix(RealMatrix m) { // for (int i = 0; i < m.getRowDimension(); i++) { @@ -1009,6 +1009,6 @@ public final class Array2DRowRealMatrixTest extends TestCase { // System.out.println(os); // } // } - + } diff --git a/src/test/java/org/apache/commons/math/linear/ArrayFieldVectorTest.java b/src/test/java/org/apache/commons/math/linear/ArrayFieldVectorTest.java index 1faa4274c..01a386370 100644 --- a/src/test/java/org/apache/commons/math/linear/ArrayFieldVectorTest.java +++ b/src/test/java/org/apache/commons/math/linear/ArrayFieldVectorTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -36,7 +36,7 @@ import org.apache.commons.math.fraction.FractionField; */ public class ArrayFieldVectorTest extends TestCase { - // + // protected Fraction[][] ma1 = { {new Fraction(1), new Fraction(2), new Fraction(3)}, {new Fraction(4), new Fraction(5), new Fraction(6)}, @@ -58,7 +58,7 @@ public class ArrayFieldVectorTest extends TestCase { {new Fraction(7), new Fraction(8), new Fraction(9)} }; - // Testclass to test the FieldVector interface + // Testclass to test the FieldVector interface // only with enough content to support the test public static class FieldVectorTestImpl> implements FieldVector, Serializable { @@ -340,7 +340,7 @@ public class ArrayFieldVectorTest extends TestCase { ArrayFieldVector v1 = new ArrayFieldVector(vec1); ArrayFieldVector v2 = new ArrayFieldVector(vec2); ArrayFieldVector v4 = new ArrayFieldVector(vec4); - FieldVectorTestImpl v2_t = new FieldVectorTestImpl(vec2); + FieldVectorTestImpl v2_t = new FieldVectorTestImpl(vec2); FieldVector v_append_1 = v1.append(v2); assertEquals(6, v_append_1.getDimension()); @@ -436,7 +436,7 @@ public class ArrayFieldVectorTest extends TestCase { } - ArrayFieldVector vout10 = (ArrayFieldVector) v1.copy(); + ArrayFieldVector vout10 = (ArrayFieldVector) v1.copy(); ArrayFieldVector vout10_2 = (ArrayFieldVector) v1.copy(); assertEquals(vout10, vout10_2); vout10_2.setEntry(0, new Fraction(11, 10)); @@ -444,7 +444,7 @@ public class ArrayFieldVectorTest extends TestCase { } - public void testMapFunctions() { + public void testMapFunctions() { ArrayFieldVector v1 = new ArrayFieldVector(vec1); //octave = v1 .+ 2.0 @@ -504,12 +504,12 @@ public class ArrayFieldVectorTest extends TestCase { } - public void testBasicFunctions() { + public void testBasicFunctions() { ArrayFieldVector v1 = new ArrayFieldVector(vec1); ArrayFieldVector v2 = new ArrayFieldVector(vec2); new ArrayFieldVector(vec_null); - FieldVectorTestImpl v2_t = new FieldVectorTestImpl(vec2); + FieldVectorTestImpl v2_t = new FieldVectorTestImpl(vec2); //octave = v1 + v2 ArrayFieldVector v_add = v1.add(v2); @@ -570,46 +570,46 @@ public class ArrayFieldVectorTest extends TestCase { Fraction[] result_projection_2 = {new Fraction(128, 77), new Fraction(160, 77), new Fraction(192, 77)}; checkArray("compare vect", v_projection_2.getData(), result_projection_2); - } + } - public void testMisc() { + public void testMisc() { ArrayFieldVector v1 = new ArrayFieldVector(vec1); ArrayFieldVector v4 = new ArrayFieldVector(vec4); FieldVector v4_2 = new ArrayFieldVector(vec4); String out1 = v1.toString(); assertTrue("some output ", out1.length()!=0); - /* + /* Fraction[] dout1 = v1.copyOut(); assertEquals(3, dout1.length); - assertNotSame("testData not same object ", v1.data, dout1); - */ + assertNotSame("testData not same object ", v1.data, dout1); + */ try { - v1.checkVectorDimensions(2); + v1.checkVectorDimensions(2); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); - } + } try { - v1.checkVectorDimensions(v4); + v1.checkVectorDimensions(v4); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); - } + } try { - v1.checkVectorDimensions(v4_2); + v1.checkVectorDimensions(v4_2); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); - } + } } @@ -617,7 +617,7 @@ public class ArrayFieldVectorTest extends TestCase { ArrayFieldVector v = new ArrayFieldVector(vec1); assertEquals(v,TestUtils.serializeAndRecover(v)); } - + /** verifies that two vectors are equals */ protected void checkArray(String msg, Fraction[] m, Fraction[] n) { if (m.length != n.length) { diff --git a/src/test/java/org/apache/commons/math/linear/ArrayRealVectorTest.java b/src/test/java/org/apache/commons/math/linear/ArrayRealVectorTest.java index 8de5a5fee..10ffbff83 100644 --- a/src/test/java/org/apache/commons/math/linear/ArrayRealVectorTest.java +++ b/src/test/java/org/apache/commons/math/linear/ArrayRealVectorTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,7 +31,7 @@ import org.apache.commons.math.TestUtils; */ public class ArrayRealVectorTest extends TestCase { - // + // protected double[][] ma1 = {{1d, 2d, 3d}, {4d, 5d, 6d}, {7d, 8d, 9d}}; protected double[] vec1 = {1d, 2d, 3d}; protected double[] vec2 = {4d, 5d, 6d}; @@ -45,7 +45,7 @@ public class ArrayRealVectorTest extends TestCase { protected double entryTolerance = 10E-16; protected double normTolerance = 10E-14; - // Testclass to test the RealVector interface + // Testclass to test the RealVector interface // only with enough content to support the test public static class RealVectorTestImpl implements RealVector, Serializable { @@ -547,7 +547,7 @@ public class ArrayRealVectorTest extends TestCase { ArrayRealVector v1 = new ArrayRealVector(vec1); ArrayRealVector v2 = new ArrayRealVector(vec2); ArrayRealVector v4 = new ArrayRealVector(vec4); - RealVectorTestImpl v2_t = new RealVectorTestImpl(vec2); + RealVectorTestImpl v2_t = new RealVectorTestImpl(vec2); RealVector v_append_1 = v1.append(v2); assertEquals("testData len", 6, v_append_1.getDimension()); @@ -643,7 +643,7 @@ public class ArrayRealVectorTest extends TestCase { } - ArrayRealVector vout10 = (ArrayRealVector) v1.copy(); + ArrayRealVector vout10 = (ArrayRealVector) v1.copy(); ArrayRealVector vout10_2 = (ArrayRealVector) v1.copy(); assertEquals(vout10, vout10_2); vout10_2.setEntry(0, 1.1); @@ -651,7 +651,7 @@ public class ArrayRealVectorTest extends TestCase { } - public void testMapFunctions() { + public void testMapFunctions() { ArrayRealVector v1 = new ArrayRealVector(vec1); //octave = v1 .+ 2.0 @@ -852,7 +852,7 @@ public class ArrayRealVectorTest extends TestCase { //octave = asin(vat) RealVector v_mapAsinToSelf = vat.copy(); - v_mapAsinToSelf.mapAsinToSelf(); + v_mapAsinToSelf.mapAsinToSelf(); double[] result_mapAsinToSelf = {0.0d,5.235987755982989e-01d,1.570796326794897e+00d}; assertClose("compare vectors" ,result_mapAsinToSelf,v_mapAsinToSelf.getData(),normTolerance); @@ -979,12 +979,12 @@ public class ArrayRealVectorTest extends TestCase { } - public void testBasicFunctions() { + public void testBasicFunctions() { ArrayRealVector v1 = new ArrayRealVector(vec1); ArrayRealVector v2 = new ArrayRealVector(vec2); ArrayRealVector v_null = new ArrayRealVector(vec_null); - RealVectorTestImpl v2_t = new RealVectorTestImpl(vec2); + RealVectorTestImpl v2_t = new RealVectorTestImpl(vec2); //octave = sqrt(sumsq(v1)) double d_getNorm = v1.getNorm(); @@ -1070,7 +1070,7 @@ public class ArrayRealVectorTest extends TestCase { assertEquals("compare val ",4d, m_outerProduct_2.getEntry(0,0)); RealVector v_unitVector = v1.unitVector(); - RealVector v_unitVector_2 = v1.mapDivide(v1.getNorm()); + RealVector v_unitVector_2 = v1.mapDivide(v1.getNorm()); assertClose("compare vect" ,v_unitVector.getData(),v_unitVector_2.getData(),normTolerance); try { @@ -1102,46 +1102,46 @@ public class ArrayRealVectorTest extends TestCase { double[] result_projection_2 = {1.662337662337662, 2.0779220779220777, 2.493506493506493}; assertClose("compare vect", v_projection_2.getData(), result_projection_2, normTolerance); - } + } - public void testMisc() { + public void testMisc() { ArrayRealVector v1 = new ArrayRealVector(vec1); ArrayRealVector v4 = new ArrayRealVector(vec4); RealVector v4_2 = new ArrayRealVector(vec4); String out1 = v1.toString(); assertTrue("some output ", out1.length()!=0); - /* + /* double[] dout1 = v1.copyOut(); assertEquals("testData len", 3, dout1.length); - assertNotSame("testData not same object ", v1.data, dout1); - */ + assertNotSame("testData not same object ", v1.data, dout1); + */ try { - v1.checkVectorDimensions(2); + v1.checkVectorDimensions(2); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); - } + } try { - v1.checkVectorDimensions(v4); + v1.checkVectorDimensions(v4); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); - } + } try { - v1.checkVectorDimensions(v4_2); + v1.checkVectorDimensions(v4_2); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); - } + } } @@ -1176,8 +1176,8 @@ public class ArrayRealVectorTest extends TestCase { ArrayRealVector v = new ArrayRealVector(new double[] { 0, 1, 2 }); assertEquals(v,TestUtils.serializeAndRecover(v)); } - - + + /** verifies that two vectors are close (sup norm) */ protected void assertClose(String msg, double[] m, double[] n, double tolerance) { diff --git a/src/test/java/org/apache/commons/math/linear/BiDiagonalTransformerTest.java b/src/test/java/org/apache/commons/math/linear/BiDiagonalTransformerTest.java index be3416b04..4009ac9d6 100644 --- a/src/test/java/org/apache/commons/math/linear/BiDiagonalTransformerTest.java +++ b/src/test/java/org/apache/commons/math/linear/BiDiagonalTransformerTest.java @@ -92,7 +92,7 @@ public class BiDiagonalTransformerTest extends TestCase { private void checkOrthogonal(RealMatrix m) { RealMatrix mTm = m.transpose().multiply(m); RealMatrix id = MatrixUtils.createRealIdentityMatrix(mTm.getRowDimension()); - assertEquals(0, mTm.subtract(id).getNorm(), 1.0e-14); + assertEquals(0, mTm.subtract(id).getNorm(), 1.0e-14); } public void testBBiDiagonal() { @@ -109,7 +109,7 @@ public class BiDiagonalTransformerTest extends TestCase { if (rows < cols) { if ((i < j) || (i > j + 1)) { assertEquals(0, m.getEntry(i, j), 1.0e-16); - } + } } else { if ((i < j - 1) || (i > j)) { assertEquals(0, m.getEntry(i, j), 1.0e-16); @@ -148,7 +148,7 @@ public class BiDiagonalTransformerTest extends TestCase { assertTrue(u == transformer.getU()); assertTrue(b == transformer.getB()); assertTrue(v == transformer.getV()); - + } public void testUpperOrLower() { diff --git a/src/test/java/org/apache/commons/math/linear/BigMatrixImplTest.java b/src/test/java/org/apache/commons/math/linear/BigMatrixImplTest.java index 6a3f1a42f..d4a066bda 100644 --- a/src/test/java/org/apache/commons/math/linear/BigMatrixImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/BigMatrixImplTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,48 +30,48 @@ import java.math.BigDecimal; */ @Deprecated public final class BigMatrixImplTest extends TestCase { - + // Test data for String constructors protected String[][] testDataString = { {"1","2","3"}, {"2","5","3"}, {"1","0","8"} }; - + // 3 x 3 identity matrix protected double[][] id = { {1d,0d,0d}, {0d,1d,0d}, {0d,0d,1d} }; - + // Test data for group operations protected double[][] testData = { {1d,2d,3d}, {2d,5d,3d}, {1d,0d,8d} }; protected double[][] testDataLU = {{2d, 5d, 3d}, {.5d, -2.5d, 6.5d}, {0.5d, 0.2d, .2d}}; protected double[][] testDataPlus2 = { {3d,4d,5d}, {4d,7d,5d}, {3d,2d,10d} }; - protected double[][] testDataMinus = { {-1d,-2d,-3d}, {-2d,-5d,-3d}, + protected double[][] testDataMinus = { {-1d,-2d,-3d}, {-2d,-5d,-3d}, {-1d,0d,-8d} }; protected double[] testDataRow1 = {1d,2d,3d}; protected double[] testDataCol3 = {3d,3d,8d}; - protected double[][] testDataInv = + protected double[][] testDataInv = { {-40d,16d,9d}, {13d,-5d,-3d}, {5d,-2d,-1d} }; protected double[] preMultTest = {8,12,33}; protected double[][] testData2 ={ {1d,2d,3d}, {2d,5d,3d}}; protected double[][] testData2T = { {1d,2d}, {2d,5d}, {3d,3d}}; - protected double[][] testDataPlusInv = + protected double[][] testDataPlusInv = { {-39d,18d,12d}, {15d,0d,0d}, {6d,-2d,7d} }; - + // lu decomposition tests protected double[][] luData = { {2d,3d,3d}, {0d,5d,7d}, {6d,9d,8d} }; protected double[][] luDataLUDecomposition = { {6d,9d,8d}, {0d,5d,7d}, {0.33333333333333,0d,0.33333333333333} }; - + // singular matrices protected double[][] singular = { {2d,3d}, {2d,3d} }; protected double[][] bigSingular = {{1d,2d,3d,4d}, {2d,5d,3d,4d}, {7d,3d,256d,1930d}, {3d,7d,6d,8d}}; // 4th row = 1st + 2nd protected double[][] detData = { {1d,2d,3d}, {4d,5d,6d}, {7d,8d,10d} }; protected double[][] detData2 = { {1d, 3d}, {2d, 4d}}; - + // vectors protected double[] testVector = {1,2,3}; protected double[] testVector2 = {1,2,3,4}; - + // submatrix accessor tests protected double[][] subTestData = {{1, 2, 3, 4}, {1.5, 2.5, 3.5, 4.5}, - {2, 4, 6, 8}, {4, 5, 6, 7}}; + {2, 4, 6, 8}, {4, 5, 6, 7}}; // array selections protected double[][] subRows02Cols13 = { {2, 4}, {4, 8}}; protected double[][] subRows03Cols12 = { {2, 3}, {5, 6}}; @@ -89,15 +89,15 @@ public final class BigMatrixImplTest extends TestCase { // column matrices protected double[][] subColumn1 = {{2}, {2.5}, {4}, {5}}; protected double[][] subColumn3 = {{4}, {4.5}, {8}, {7}}; - + // tolerances protected double entryTolerance = 10E-16; protected double normTolerance = 10E-14; - + public BigMatrixImplTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(BigMatrixImplTest.class); suite.setName("BigMatrixImpl Tests"); @@ -149,8 +149,8 @@ public final class BigMatrixImplTest extends TestCase { assertEquals("testData2 row dimension",m2.getRowDimension(),2); assertEquals("testData2 column dimension",m2.getColumnDimension(),3); assertTrue("testData2 is not square",!m2.isSquare()); - } - + } + /** test copy functions */ public void testCopyFunctions() { BigMatrixImpl m1 = new BigMatrixImpl(testData); @@ -160,7 +160,7 @@ public final class BigMatrixImplTest extends TestCase { BigMatrixImpl m4 = new BigMatrixImpl(m3.getData(), false); assertEquals(m4,m3); } - + /** test constructors */ public void testConstructors() { BigMatrix m1 = new BigMatrixImpl(testData); @@ -211,7 +211,7 @@ public final class BigMatrixImplTest extends TestCase { // expected } } - + /** test add */ public void testAdd() { BigMatrixImpl m = new BigMatrixImpl(testData); @@ -224,9 +224,9 @@ public final class BigMatrixImplTest extends TestCase { testDataPlusInv[row][col],sumEntries[row][col], entryTolerance); } - } + } } - + /** test add failure */ public void testAddFail() { BigMatrixImpl m = new BigMatrixImpl(testData); @@ -238,7 +238,7 @@ public final class BigMatrixImplTest extends TestCase { // ignored } } - + /** test norm */ public void testNorm() { BigMatrixImpl m = new BigMatrixImpl(testData); @@ -246,7 +246,7 @@ public final class BigMatrixImplTest extends TestCase { assertEquals("testData norm",14d,m.getNorm().doubleValue(),entryTolerance); assertEquals("testData2 norm",7d,m2.getNorm().doubleValue(),entryTolerance); } - + /** test m-n = m + -n */ public void testPlusMinus() { BigMatrixImpl m = new BigMatrixImpl(testData); @@ -258,9 +258,9 @@ public final class BigMatrixImplTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + /** test multiply */ public void testMultiply() { BigMatrixImpl m = new BigMatrixImpl(testData); @@ -276,28 +276,28 @@ public final class BigMatrixImplTest extends TestCase { assertClose("identity multiply",identity.multiply(mInv), mInv,entryTolerance); assertClose("identity multiply",m2.multiply(identity), - m2,entryTolerance); + m2,entryTolerance); try { m.multiply(new BigMatrixImpl(bigSingular)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } - } - + } + } + //Additional Test for BigMatrixImplTest.testMultiply private double[][] d3 = new double[][] {{1,2,3,4},{5,6,7,8}}; private double[][] d4 = new double[][] {{1},{2},{3},{4}}; private double[][] d5 = new double[][] {{30},{70}}; - - public void testMultiply2() { + + public void testMultiply2() { BigMatrix m3 = new BigMatrixImpl(d3); BigMatrix m4 = new BigMatrixImpl(d4); BigMatrix m5 = new BigMatrixImpl(d5); assertClose("m3*m4=m5", m3.multiply(m4), m5, entryTolerance); - } - + } + /** test isSingular */ public void testIsSingular() { BigMatrixImpl m = new BigMatrixImpl(singular); @@ -309,14 +309,14 @@ public final class BigMatrixImplTest extends TestCase { m = new BigMatrixImpl(testData); assertTrue("testData nonsingular",!m.isSingular()); } - + /** test inverse */ public void testInverse() { BigMatrixImpl m = new BigMatrixImpl(testData); BigMatrix mInv = new BigMatrixImpl(testDataInv); assertClose("inverse",mInv,m.inverse(),normTolerance); assertClose("inverse^2",m,m.inverse().inverse(),10E-12); - + // Not square m = new BigMatrixImpl(testData2); try { @@ -325,7 +325,7 @@ public final class BigMatrixImplTest extends TestCase { } catch (InvalidMatrixException ex) { // expected } - + // Singular m = new BigMatrixImpl(singular); try { @@ -335,7 +335,7 @@ public final class BigMatrixImplTest extends TestCase { // expected } } - + /** test solve */ public void testSolve() { BigMatrixImpl m = new BigMatrixImpl(testData); @@ -350,7 +350,7 @@ public final class BigMatrixImplTest extends TestCase { fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } BigMatrix bs = new BigMatrixImpl(bigSingular); try { bs.solve(bs); @@ -369,22 +369,22 @@ public final class BigMatrixImplTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } try { (new BigMatrixImpl(testData2)).luDecompose(); fail("Expecting InvalidMatrixException"); } catch (InvalidMatrixException ex) { // ignored - } + } } - + /** test determinant */ - public void testDeterminant() { + public void testDeterminant() { BigMatrix m = new BigMatrixImpl(bigSingular); assertEquals("singular determinant",0,m.getDeterminant().doubleValue(),0); m = new BigMatrixImpl(detData); assertEquals("nonsingular test",-3d,m.getDeterminant().doubleValue(),normTolerance); - + // Examples verified against R (version 1.8.1, Red Hat Linux 9) m = new BigMatrixImpl(detData2); assertEquals("nonsingular R test 1",-2d,m.getDeterminant().doubleValue(),normTolerance); @@ -396,9 +396,9 @@ public final class BigMatrixImplTest extends TestCase { fail("Expecting InvalidMatrixException, got " + d); } catch (InvalidMatrixException ex) { // ignored - } + } } - + /** test trace */ public void testTrace() { BigMatrix m = new BigMatrixImpl(id); @@ -409,16 +409,16 @@ public final class BigMatrixImplTest extends TestCase { fail("Expecting NonSquareMatrixException, got " + t); } catch (NonSquareMatrixException ex) { // ignored - } + } } - + /** test sclarAdd */ public void testScalarAdd() { BigMatrix m = new BigMatrixImpl(testData); assertClose("scalar add",new BigMatrixImpl(testDataPlus2), m.scalarAdd(new BigDecimal(2d)),entryTolerance); } - + /** test operate */ public void testOperate() { BigMatrix m = new BigMatrixImpl(id); @@ -430,7 +430,7 @@ public final class BigMatrixImplTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } /** test issue MATH-209 */ @@ -446,7 +446,7 @@ public final class BigMatrixImplTest extends TestCase { assertEquals( 7.0, b[1].doubleValue(), 1.0e-12); assertEquals(11.0, b[2].doubleValue(), 1.0e-12); } - + /** test transpose */ public void testTranspose() { BigMatrix m = new BigMatrixImpl(testData); @@ -456,7 +456,7 @@ public final class BigMatrixImplTest extends TestCase { BigMatrix mt = new BigMatrixImpl(testData2T); assertClose("transpose",mt,m.transpose(),normTolerance); } - + /** test preMultiply by vector */ public void testPremultiplyVector() { BigMatrix m = new BigMatrixImpl(testData); @@ -469,13 +469,13 @@ public final class BigMatrixImplTest extends TestCase { // ignored } } - + public void testPremultiply() { BigMatrix m3 = new BigMatrixImpl(d3); BigMatrix m4 = new BigMatrixImpl(d4); BigMatrix m5 = new BigMatrixImpl(d5); assertClose("m3*m4=m5", m4.preMultiply(m3), m5, entryTolerance); - + BigMatrixImpl m = new BigMatrixImpl(testData); BigMatrixImpl mInv = new BigMatrixImpl(testDataInv); BigMatrixImpl identity = new BigMatrixImpl(id); @@ -493,9 +493,9 @@ public final class BigMatrixImplTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + public void testGetVectors() { BigMatrix m = new BigMatrixImpl(testData); assertClose("get row",m.getRowAsDoubleArray(0),testDataRow1,entryTolerance); @@ -513,7 +513,7 @@ public final class BigMatrixImplTest extends TestCase { // ignored } } - + public void testLUDecomposition() throws Exception { BigMatrixImpl m = new BigMatrixImpl(testData); BigMatrix lu = m.getLUMatrix(); @@ -544,7 +544,7 @@ public final class BigMatrixImplTest extends TestCase { // expected } } - + /** * test submatrix accessors */ @@ -558,25 +558,25 @@ public final class BigMatrixImplTest extends TestCase { BigMatrix mRows03Cols123 = new BigMatrixImpl(subRows03Cols123); BigMatrix mRows20Cols123 = new BigMatrixImpl(subRows20Cols123); BigMatrix mRows31Cols31 = new BigMatrixImpl(subRows31Cols31); - assertEquals("Rows23Cols00", mRows23Cols00, + assertEquals("Rows23Cols00", mRows23Cols00, m.getSubMatrix(2 , 3 , 0, 0)); - assertEquals("Rows00Cols33", mRows00Cols33, + assertEquals("Rows00Cols33", mRows00Cols33, m.getSubMatrix(0 , 0 , 3, 3)); assertEquals("Rows01Cols23", mRows01Cols23, - m.getSubMatrix(0 , 1 , 2, 3)); + m.getSubMatrix(0 , 1 , 2, 3)); assertEquals("Rows02Cols13", mRows02Cols13, - m.getSubMatrix(new int[] {0,2}, new int[] {1,3})); + m.getSubMatrix(new int[] {0,2}, new int[] {1,3})); assertEquals("Rows03Cols12", mRows03Cols12, - m.getSubMatrix(new int[] {0,3}, new int[] {1,2})); + m.getSubMatrix(new int[] {0,3}, new int[] {1,2})); assertEquals("Rows03Cols123", mRows03Cols123, - m.getSubMatrix(new int[] {0,3}, new int[] {1,2,3})); + m.getSubMatrix(new int[] {0,3}, new int[] {1,2,3})); assertEquals("Rows20Cols123", mRows20Cols123, - m.getSubMatrix(new int[] {2,0}, new int[] {1,2,3})); + m.getSubMatrix(new int[] {2,0}, new int[] {1,2,3})); assertEquals("Rows31Cols31", mRows31Cols31, - m.getSubMatrix(new int[] {3,1}, new int[] {3,1})); + m.getSubMatrix(new int[] {3,1}, new int[] {3,1})); assertEquals("Rows31Cols31", mRows31Cols31, - m.getSubMatrix(new int[] {3,1}, new int[] {3,1})); - + m.getSubMatrix(new int[] {3,1}, new int[] {3,1})); + try { m.getSubMatrix(1,0,2,4); fail("Expecting MatrixIndexException"); @@ -614,14 +614,14 @@ public final class BigMatrixImplTest extends TestCase { // expected } } - + public void testGetColumnMatrix() { BigMatrix m = new BigMatrixImpl(subTestData); BigMatrix mColumn1 = new BigMatrixImpl(subColumn1); BigMatrix mColumn3 = new BigMatrixImpl(subColumn3); - assertEquals("Column1", mColumn1, + assertEquals("Column1", mColumn1, m.getColumnMatrix(1)); - assertEquals("Column3", mColumn3, + assertEquals("Column3", mColumn3, m.getColumnMatrix(3)); try { m.getColumnMatrix(-1); @@ -636,14 +636,14 @@ public final class BigMatrixImplTest extends TestCase { // expected } } - + public void testGetRowMatrix() { BigMatrix m = new BigMatrixImpl(subTestData); BigMatrix mRow0 = new BigMatrixImpl(subRow0); BigMatrix mRow3 = new BigMatrixImpl(subRow3); - assertEquals("Row0", mRow0, + assertEquals("Row0", mRow0, m.getRowMatrix(0)); - assertEquals("Row3", mRow3, + assertEquals("Row3", mRow3, m.getRowMatrix(3)); try { m.getRowMatrix(-1); @@ -658,7 +658,7 @@ public final class BigMatrixImplTest extends TestCase { // expected } } - + public void testEqualsAndHashCode() { BigMatrixImpl m = new BigMatrixImpl(testData); BigMatrixImpl m1 = (BigMatrixImpl) m.copy(); @@ -676,7 +676,7 @@ public final class BigMatrixImplTest extends TestCase { assertTrue(m.hashCode() != m1.hashCode()); assertFalse(m.equals(m1)); } - + public void testToString() { BigMatrixImpl m = new BigMatrixImpl(testData); assertEquals("BigMatrixImpl{{1,2,3},{2,5,3},{1,0,8}}", @@ -685,28 +685,28 @@ public final class BigMatrixImplTest extends TestCase { assertEquals("BigMatrixImpl{}", m.toString()); } - + public void testSetSubMatrix() throws Exception { - BigDecimal[][] detData3 = + BigDecimal[][] detData3 = MatrixUtils.createBigMatrix(detData2).getData(); BigMatrixImpl m = new BigMatrixImpl(testData); m.setSubMatrix(detData3,1,1); BigMatrix expected = MatrixUtils.createBigMatrix (new double[][] {{1.0,2.0,3.0},{2.0,1.0,3.0},{1.0,2.0,4.0}}); - assertEquals(expected, m); - + assertEquals(expected, m); + m.setSubMatrix(detData3,0,0); expected = MatrixUtils.createBigMatrix (new double[][] {{1.0,3.0,3.0},{2.0,4.0,3.0},{1.0,2.0,4.0}}); - assertEquals(expected, m); - - BigDecimal[][] testDataPlus3 = + assertEquals(expected, m); + + BigDecimal[][] testDataPlus3 = MatrixUtils.createBigMatrix(testDataPlus2).getData(); - m.setSubMatrix(testDataPlus3,0,0); + m.setSubMatrix(testDataPlus3,0,0); expected = MatrixUtils.createBigMatrix (new double[][] {{3.0,4.0,5.0},{4.0,7.0,5.0},{3.0,2.0,10.0}}); - assertEquals(expected, m); - + assertEquals(expected, m); + // javadoc example BigMatrixImpl matrix = (BigMatrixImpl) MatrixUtils.createBigMatrix (new double[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1 , 2}}); @@ -718,16 +718,16 @@ public final class BigMatrixImplTest extends TestCase { new BigDecimal(3), new BigDecimal(4), new BigDecimal(8)}, {new BigDecimal(9), new BigDecimal(5) , new BigDecimal(6), new BigDecimal(2)}}); - assertEquals(expected, matrix); - + assertEquals(expected, matrix); + // dimension overflow - try { + try { m.setSubMatrix(matrix.getData(),1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - + // null try { m.setSubMatrix(null,1,1); @@ -735,7 +735,7 @@ public final class BigMatrixImplTest extends TestCase { } catch (NullPointerException e) { // expected } - + // ragged try { m.setSubMatrix(new BigDecimal[][] {{new BigDecimal(1)}, @@ -744,7 +744,7 @@ public final class BigMatrixImplTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + // empty try { m.setSubMatrix(new BigDecimal[][] {{}}, 0, 0); @@ -752,17 +752,17 @@ public final class BigMatrixImplTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + } - + //--------------- -----------------Protected methods - - /** verifies that two matrices are close (1-norm) */ + + /** verifies that two matrices are close (1-norm) */ protected void assertClose(String msg, BigMatrix m, BigMatrix n, double tolerance) { assertTrue(msg,m.subtract(n).getNorm().doubleValue() < tolerance); } - + /** verifies that two vectors are close (sup norm) */ protected void assertClose(String msg, double[] m, double[] n, double tolerance) { @@ -770,18 +770,18 @@ public final class BigMatrixImplTest extends TestCase { fail("vectors not same length"); } for (int i = 0; i < m.length; i++) { - assertEquals(msg + " " + i + " elements differ", + assertEquals(msg + " " + i + " elements differ", m[i],n[i],tolerance); } } - + /** extracts the l and u matrices from compact lu representation */ protected void splitLU(BigMatrix lu, BigDecimal[][] lowerData, BigDecimal[][] upperData) throws InvalidMatrixException { if (!lu.isSquare() || lowerData.length != lowerData[0].length || upperData.length != upperData[0].length || lowerData.length != upperData.length || lowerData.length != lu.getRowDimension()) { throw new InvalidMatrixException("incorrect dimensions"); - } + } int n = lu.getRowDimension(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { @@ -794,11 +794,11 @@ public final class BigMatrixImplTest extends TestCase { } else { lowerData[i][j] = new BigDecimal(0); upperData[i][j] = lu.getEntry(i, j); - } + } } } } - + /** Returns the result of applying the given row permutation to the matrix */ protected BigMatrix permuteRows(BigMatrix matrix, int[] permutation) { if (!matrix.isSquare() || matrix.getRowDimension() != permutation.length) { @@ -814,7 +814,7 @@ public final class BigMatrixImplTest extends TestCase { } return new BigMatrixImpl(out); } - + /** Extracts l and u matrices from lu and verifies that matrix = l times u modulo permutation */ protected void verifyDecomposition(BigMatrix matrix, BigMatrix lu) throws Exception{ int n = matrix.getRowDimension(); @@ -828,7 +828,7 @@ public final class BigMatrixImplTest extends TestCase { assertClose("lu decomposition does not work", permuted, lower.multiply(upper), normTolerance); } - + // /** Useful for debugging */ // private void dumpMatrix(BigMatrix m) { // for (int i = 0; i < m.getRowDimension(); i++) { @@ -839,6 +839,6 @@ public final class BigMatrixImplTest extends TestCase { // System.out.println(os); // } // } - + } diff --git a/src/test/java/org/apache/commons/math/linear/BlockFieldMatrixTest.java b/src/test/java/org/apache/commons/math/linear/BlockFieldMatrixTest.java index 6a0dfd1cc..687980178 100644 --- a/src/test/java/org/apache/commons/math/linear/BlockFieldMatrixTest.java +++ b/src/test/java/org/apache/commons/math/linear/BlockFieldMatrixTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -34,14 +34,14 @@ import org.apache.commons.math.fraction.FractionField; */ public final class BlockFieldMatrixTest extends TestCase { - + // 3 x 3 identity matrix protected Fraction[][] id = { {new Fraction(1),new Fraction(0),new Fraction(0)}, {new Fraction(0),new Fraction(1),new Fraction(0)}, {new Fraction(0),new Fraction(0),new Fraction(1)} }; - + // Test data for group operations protected Fraction[][] testData = { {new Fraction(1),new Fraction(2),new Fraction(3)}, @@ -60,7 +60,7 @@ public final class BlockFieldMatrixTest extends TestCase { }; protected Fraction[][] testDataMinus = { {new Fraction(-1),new Fraction(-2),new Fraction(-3)}, - {new Fraction(-2),new Fraction(-5),new Fraction(-3)}, + {new Fraction(-2),new Fraction(-5),new Fraction(-3)}, {new Fraction(-1),new Fraction(0),new Fraction(-8)} }; protected Fraction[] testDataRow1 = {new Fraction(1),new Fraction(2),new Fraction(3)}; @@ -85,7 +85,7 @@ public final class BlockFieldMatrixTest extends TestCase { {new Fraction(15),new Fraction(0),new Fraction(0)}, {new Fraction(6),new Fraction(-2),new Fraction(7)} }; - + // lu decomposition tests protected Fraction[][] luData = { {new Fraction(2),new Fraction(3),new Fraction(3)}, @@ -97,7 +97,7 @@ public final class BlockFieldMatrixTest extends TestCase { {new Fraction(0),new Fraction(5),new Fraction(7)}, {new Fraction(1, 3),new Fraction(0),new Fraction(1, 3)} }; - + // singular matrices protected Fraction[][] singular = { {new Fraction(2),new Fraction(3)}, {new Fraction(2),new Fraction(3)} }; protected Fraction[][] bigSingular = { @@ -112,18 +112,18 @@ public final class BlockFieldMatrixTest extends TestCase { {new Fraction(7),new Fraction(8),new Fraction(10)} }; protected Fraction[][] detData2 = { {new Fraction(1), new Fraction(3)}, {new Fraction(2), new Fraction(4)}}; - + // vectors protected Fraction[] testVector = {new Fraction(1),new Fraction(2),new Fraction(3)}; protected Fraction[] testVector2 = {new Fraction(1),new Fraction(2),new Fraction(3),new Fraction(4)}; - + // submatrix accessor tests protected Fraction[][] subTestData = { {new Fraction(1), new Fraction(2), new Fraction(3), new Fraction(4)}, {new Fraction(3, 2), new Fraction(5, 2), new Fraction(7, 2), new Fraction(9, 2)}, {new Fraction(2), new Fraction(4), new Fraction(6), new Fraction(8)}, {new Fraction(4), new Fraction(5), new Fraction(6), new Fraction(7)} - }; + }; // array selections protected Fraction[][] subRows02Cols13 = { {new Fraction(2), new Fraction(4)}, {new Fraction(4), new Fraction(8)}}; protected Fraction[][] subRows03Cols12 = { {new Fraction(2), new Fraction(3)}, {new Fraction(5), new Fraction(6)}}; @@ -147,21 +147,21 @@ public final class BlockFieldMatrixTest extends TestCase { // column matrices protected Fraction[][] subColumn1 = {{new Fraction(2)}, {new Fraction(5, 2)}, {new Fraction(4)}, {new Fraction(5)}}; protected Fraction[][] subColumn3 = {{new Fraction(4)}, {new Fraction(9, 2)}, {new Fraction(8)}, {new Fraction(7)}}; - + // tolerances protected double entryTolerance = 10E-16; protected double normTolerance = 10E-14; - + public BlockFieldMatrixTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(BlockFieldMatrixTest.class); suite.setName("BlockFieldMatrix Tests"); return suite; } - + /** test dimensions */ public void testDimensions() { BlockFieldMatrix m = new BlockFieldMatrix(testData); @@ -172,8 +172,8 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals("testData2 row dimension",m2.getRowDimension(),2); assertEquals("testData2 column dimension",m2.getColumnDimension(),3); assertTrue("testData2 is not square",!m2.isSquare()); - } - + } + /** test copy functions */ public void testCopyFunctions() { Random r = new Random(66636328996002l); @@ -183,8 +183,8 @@ public final class BlockFieldMatrixTest extends TestCase { BlockFieldMatrix m3 = new BlockFieldMatrix(testData); BlockFieldMatrix m4 = new BlockFieldMatrix(m3.getData()); assertEquals(m3, m4); - } - + } + /** test add */ public void testAdd() { BlockFieldMatrix m = new BlockFieldMatrix(testData); @@ -195,9 +195,9 @@ public final class BlockFieldMatrixTest extends TestCase { for (int col = 0; col < m.getColumnDimension(); col++) { assertEquals(testDataPlusInv[row][col],sumEntries[row][col]); } - } + } } - + /** test add failure */ public void testAddFail() { BlockFieldMatrix m = new BlockFieldMatrix(testData); @@ -209,20 +209,20 @@ public final class BlockFieldMatrixTest extends TestCase { // ignored } } - + /** test m-n = m + -n */ public void testPlusMinus() { BlockFieldMatrix m = new BlockFieldMatrix(testData); BlockFieldMatrix m2 = new BlockFieldMatrix(testDataInv); - TestUtils.assertEquals(m.subtract(m2), m2.scalarMultiply(new Fraction(-1)).add(m)); + TestUtils.assertEquals(m.subtract(m2), m2.scalarMultiply(new Fraction(-1)).add(m)); try { m.subtract(new BlockFieldMatrix(testData2)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + /** test multiply */ public void testMultiply() { BlockFieldMatrix m = new BlockFieldMatrix(testData); @@ -233,13 +233,13 @@ public final class BlockFieldMatrixTest extends TestCase { TestUtils.assertEquals(mInv.multiply(m), identity); TestUtils.assertEquals(m.multiply(identity), m); TestUtils.assertEquals(identity.multiply(mInv), mInv); - TestUtils.assertEquals(m2.multiply(identity), m2); + TestUtils.assertEquals(m2.multiply(identity), m2); try { m.multiply(new BlockFieldMatrix(bigSingular)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } } public void testSeveralBlocks() { @@ -340,14 +340,14 @@ public final class BlockFieldMatrixTest extends TestCase { {new Fraction(4)} }; private Fraction[][] d5 = new Fraction[][] {{new Fraction(30)},{new Fraction(70)}}; - - public void testMultiply2() { - FieldMatrix m3 = new BlockFieldMatrix(d3); + + public void testMultiply2() { + FieldMatrix m3 = new BlockFieldMatrix(d3); FieldMatrix m4 = new BlockFieldMatrix(d4); FieldMatrix m5 = new BlockFieldMatrix(d5); TestUtils.assertEquals(m3.multiply(m4), m5); - } - + } + /** test trace */ public void testTrace() { FieldMatrix m = new BlockFieldMatrix(id); @@ -358,16 +358,16 @@ public final class BlockFieldMatrixTest extends TestCase { fail("Expecting NonSquareMatrixException"); } catch (NonSquareMatrixException ex) { // ignored - } + } } - + /** test scalarAdd */ public void testScalarAdd() { FieldMatrix m = new BlockFieldMatrix(testData); TestUtils.assertEquals(new BlockFieldMatrix(testDataPlus2), m.scalarAdd(new Fraction(2))); } - + /** test operate */ public void testOperate() { FieldMatrix m = new BlockFieldMatrix(id); @@ -379,7 +379,7 @@ public final class BlockFieldMatrixTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } public void testOperateLarge() { @@ -421,10 +421,10 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals( new Fraction(7), b[1]); assertEquals(new Fraction(11), b[2]); } - + /** test transpose */ public void testTranspose() { - FieldMatrix m = new BlockFieldMatrix(testData); + FieldMatrix m = new BlockFieldMatrix(testData); FieldMatrix mIT = new FieldLUDecompositionImpl(m).getSolver().getInverse().transpose(); FieldMatrix mTI = new FieldLUDecompositionImpl(m.transpose()).getSolver().getInverse(); TestUtils.assertEquals(mIT, mTI); @@ -432,7 +432,7 @@ public final class BlockFieldMatrixTest extends TestCase { FieldMatrix mt = new BlockFieldMatrix(testData2T); TestUtils.assertEquals(mt, m.transpose()); } - + /** test preMultiply by vector */ public void testPremultiplyVector() { FieldMatrix m = new BlockFieldMatrix(testData); @@ -447,13 +447,13 @@ public final class BlockFieldMatrixTest extends TestCase { // ignored } } - + public void testPremultiply() { - FieldMatrix m3 = new BlockFieldMatrix(d3); + FieldMatrix m3 = new BlockFieldMatrix(d3); FieldMatrix m4 = new BlockFieldMatrix(d4); FieldMatrix m5 = new BlockFieldMatrix(d5); TestUtils.assertEquals(m4.preMultiply(m3), m5); - + BlockFieldMatrix m = new BlockFieldMatrix(testData); BlockFieldMatrix mInv = new BlockFieldMatrix(testDataInv); BlockFieldMatrix identity = new BlockFieldMatrix(id); @@ -466,9 +466,9 @@ public final class BlockFieldMatrixTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + public void testGetVectors() { FieldMatrix m = new BlockFieldMatrix(testData); TestUtils.assertEquals(m.getRow(0), testDataRow1); @@ -486,7 +486,7 @@ public final class BlockFieldMatrixTest extends TestCase { // ignored } } - + public void testGetEntry() { FieldMatrix m = new BlockFieldMatrix(testData); assertEquals(m.getEntry(0,1),new Fraction(2)); @@ -497,7 +497,7 @@ public final class BlockFieldMatrixTest extends TestCase { // expected } } - + /** test examples in user guide */ public void testExamples() { // Create a real matrix with two rows and three columns @@ -518,10 +518,10 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals(2, p.getRowDimension()); assertEquals(2, p.getColumnDimension()); // Invert p - FieldMatrix pInverse = new FieldLUDecompositionImpl(p).getSolver().getInverse(); + FieldMatrix pInverse = new FieldLUDecompositionImpl(p).getSolver().getInverse(); assertEquals(2, pInverse.getRowDimension()); assertEquals(2, pInverse.getColumnDimension()); - + // Solve example Fraction[][] coefficientsData = { {new Fraction(2), new Fraction(3), new Fraction(-2)}, @@ -542,22 +542,22 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals(new Fraction(4).multiply(solution[0]). subtract(new Fraction(3).multiply(solution[1])). subtract(new Fraction(5).multiply(solution[2])), - constants[2]); - + constants[2]); + } - + // test submatrix accessors public void testGetSubMatrix() { FieldMatrix m = new BlockFieldMatrix(subTestData); checkGetSubMatrix(m, subRows23Cols00, 2 , 3 , 0, 0); checkGetSubMatrix(m, subRows00Cols33, 0 , 0 , 3, 3); - checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3); - checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); - checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); - checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); - checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3); + checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); + checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); + checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); + checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); checkGetSubMatrix(m, null, 1, 0, 2, 4); checkGetSubMatrix(m, null, -1, 1, 2, 2); checkGetSubMatrix(m, null, 1, 0, 2, 2); @@ -581,7 +581,7 @@ public final class BlockFieldMatrixTest extends TestCase { } } } - + private void checkGetSubMatrix(FieldMatrix m, Fraction[][] reference, int[] selectedRows, int[] selectedColumns) { try { @@ -623,14 +623,14 @@ public final class BlockFieldMatrixTest extends TestCase { FieldMatrix m = new BlockFieldMatrix(subTestData); checkCopy(m, subRows23Cols00, 2 , 3 , 0, 0); checkCopy(m, subRows00Cols33, 0 , 0 , 3, 3); - checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3); - checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); - checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); - checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); - checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - + checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3); + checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); + checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); + checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); + checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkCopy(m, null, 1, 0, 2, 4); checkCopy(m, null, -1, 1, 2, 2); checkCopy(m, null, 1, 0, 2, 2); @@ -657,7 +657,7 @@ public final class BlockFieldMatrixTest extends TestCase { } } } - + private void checkCopy(FieldMatrix m, Fraction[][] reference, int[] selectedRows, int[] selectedColumns) { try { @@ -716,7 +716,7 @@ public final class BlockFieldMatrixTest extends TestCase { // expected } } - + public void testGetSetRowMatrixLarge() { int n = 3 * BlockFieldMatrix.BLOCK_SIZE; FieldMatrix m = @@ -737,7 +737,7 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals(sub, m.getRowMatrix(2)); } - + public void testGetColumnMatrix() { FieldMatrix m = new BlockFieldMatrix(subTestData); FieldMatrix mColumn1 = new BlockFieldMatrix(subColumn1); @@ -798,7 +798,7 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals(sub, m.getColumnMatrix(2)); } - + public void testGetRowVector() { FieldMatrix m = new BlockFieldMatrix(subTestData); FieldVector mRow0 = new ArrayFieldVector(subRow0[0]); @@ -857,7 +857,7 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals(sub, m.getRowVector(2)); } - + public void testGetColumnVector() { FieldMatrix m = new BlockFieldMatrix(subTestData); FieldVector mColumn1 = columnToVector(subColumn1); @@ -916,7 +916,7 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals(sub, m.getColumnVector(2)); } - + private FieldVector columnToVector(Fraction[][] column) { Fraction[] data = new Fraction[column.length]; for (int i = 0; i < data.length; ++i) { @@ -981,7 +981,7 @@ public final class BlockFieldMatrixTest extends TestCase { checkArrays(sub, m.getRow(2)); } - + public void testGetColumn() { FieldMatrix m = new BlockFieldMatrix(subTestData); Fraction[] mColumn1 = columnToArray(subColumn1); @@ -1041,7 +1041,7 @@ public final class BlockFieldMatrixTest extends TestCase { checkArrays(sub, m.getColumn(2)); } - + private Fraction[] columnToArray(Fraction[][] column) { Fraction[] data = new Fraction[column.length]; for (int i = 0; i < data.length; ++i) { @@ -1053,10 +1053,10 @@ public final class BlockFieldMatrixTest extends TestCase { private void checkArrays(Fraction[] expected, Fraction[] actual) { assertEquals(expected.length, actual.length); for (int i = 0; i < expected.length; ++i) { - assertEquals(expected[i], actual[i]); + assertEquals(expected[i], actual[i]); } } - + public void testEqualsAndHashCode() { BlockFieldMatrix m = new BlockFieldMatrix(testData); BlockFieldMatrix m1 = (BlockFieldMatrix) m.copy(); @@ -1067,31 +1067,31 @@ public final class BlockFieldMatrixTest extends TestCase { assertEquals(m, m1); assertFalse(m.equals(null)); assertFalse(m.equals(mt)); - assertFalse(m.equals(new BlockFieldMatrix(bigSingular))); + assertFalse(m.equals(new BlockFieldMatrix(bigSingular))); } - + public void testToString() { BlockFieldMatrix m = new BlockFieldMatrix(testData); assertEquals("BlockFieldMatrix{{1,2,3},{2,5,3},{1,0,8}}", m.toString()); } - + public void testSetSubMatrix() throws Exception { BlockFieldMatrix m = new BlockFieldMatrix(testData); m.setSubMatrix(detData2,1,1); FieldMatrix expected = new BlockFieldMatrix (new Fraction[][] {{new Fraction(1),new Fraction(2),new Fraction(3)},{new Fraction(2),new Fraction(1),new Fraction(3)},{new Fraction(1),new Fraction(2),new Fraction(4)}}); - assertEquals(expected, m); - + assertEquals(expected, m); + m.setSubMatrix(detData2,0,0); expected = new BlockFieldMatrix (new Fraction[][] {{new Fraction(1),new Fraction(3),new Fraction(3)},{new Fraction(2),new Fraction(4),new Fraction(3)},{new Fraction(1),new Fraction(2),new Fraction(4)}}); - assertEquals(expected, m); - - m.setSubMatrix(testDataPlus2,0,0); + assertEquals(expected, m); + + m.setSubMatrix(testDataPlus2,0,0); expected = new BlockFieldMatrix (new Fraction[][] {{new Fraction(3),new Fraction(4),new Fraction(5)},{new Fraction(4),new Fraction(7),new Fraction(5)},{new Fraction(3),new Fraction(2),new Fraction(10)}}); - assertEquals(expected, m); - + assertEquals(expected, m); + // javadoc example BlockFieldMatrix matrix = new BlockFieldMatrix(new Fraction[][] { @@ -1109,29 +1109,29 @@ public final class BlockFieldMatrixTest extends TestCase { {new Fraction(5), new Fraction(3), new Fraction(4), new Fraction(8)}, {new Fraction(9), new Fraction(5) ,new Fraction(6), new Fraction(2)} }); - assertEquals(expected, matrix); + assertEquals(expected, matrix); // dimension overflow - try { + try { m.setSubMatrix(testData,1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } // dimension underflow - try { + try { m.setSubMatrix(testData,-1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - try { + try { m.setSubMatrix(testData,1,-1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - + // null try { m.setSubMatrix(null,1,1); @@ -1139,7 +1139,7 @@ public final class BlockFieldMatrixTest extends TestCase { } catch (NullPointerException e) { // expected } - + // ragged try { m.setSubMatrix(new Fraction[][] {{new Fraction(1)}, {new Fraction(2), new Fraction(3)}}, 0, 0); @@ -1147,7 +1147,7 @@ public final class BlockFieldMatrixTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + // empty try { m.setSubMatrix(new Fraction[][] {{}}, 0, 0); @@ -1155,7 +1155,7 @@ public final class BlockFieldMatrixTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + } public void testWalk() { @@ -1174,11 +1174,11 @@ public final class BlockFieldMatrixTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(new Fraction(0), m.getEntry(i, 0)); + assertEquals(new Fraction(0), m.getEntry(i, 0)); assertEquals(new Fraction(0), m.getEntry(i, columns - 1)); } for (int j = 0; j < columns; ++j) { - assertEquals(new Fraction(0), m.getEntry(0, j)); + assertEquals(new Fraction(0), m.getEntry(0, j)); assertEquals(new Fraction(0), m.getEntry(rows - 1, j)); } @@ -1194,11 +1194,11 @@ public final class BlockFieldMatrixTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(new Fraction(0), m.getEntry(i, 0)); + assertEquals(new Fraction(0), m.getEntry(i, 0)); assertEquals(new Fraction(0), m.getEntry(i, columns - 1)); } for (int j = 0; j < columns; ++j) { - assertEquals(new Fraction(0), m.getEntry(0, j)); + assertEquals(new Fraction(0), m.getEntry(0, j)); assertEquals(new Fraction(0), m.getEntry(rows - 1, j)); } @@ -1214,11 +1214,11 @@ public final class BlockFieldMatrixTest extends TestCase { m.walkInRowOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(new Fraction(0), m.getEntry(i, 0)); + assertEquals(new Fraction(0), m.getEntry(i, 0)); assertEquals(new Fraction(0), m.getEntry(i, columns - 1)); } for (int j = 0; j < columns; ++j) { - assertEquals(new Fraction(0), m.getEntry(0, j)); + assertEquals(new Fraction(0), m.getEntry(0, j)); assertEquals(new Fraction(0), m.getEntry(rows - 1, j)); } @@ -1234,11 +1234,11 @@ public final class BlockFieldMatrixTest extends TestCase { m.walkInColumnOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(new Fraction(0), m.getEntry(i, 0)); + assertEquals(new Fraction(0), m.getEntry(i, 0)); assertEquals(new Fraction(0), m.getEntry(i, columns - 1)); } for (int j = 0; j < columns; ++j) { - assertEquals(new Fraction(0), m.getEntry(0, j)); + assertEquals(new Fraction(0), m.getEntry(0, j)); assertEquals(new Fraction(0), m.getEntry(rows - 1, j)); } @@ -1290,6 +1290,6 @@ public final class BlockFieldMatrixTest extends TestCase { } return m; } - + } diff --git a/src/test/java/org/apache/commons/math/linear/BlockRealMatrixTest.java b/src/test/java/org/apache/commons/math/linear/BlockRealMatrixTest.java index 67a0aa4b6..a8fa1d65b 100644 --- a/src/test/java/org/apache/commons/math/linear/BlockRealMatrixTest.java +++ b/src/test/java/org/apache/commons/math/linear/BlockRealMatrixTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,45 +32,45 @@ import org.apache.commons.math.TestUtils; */ public final class BlockRealMatrixTest extends TestCase { - + // 3 x 3 identity matrix protected double[][] id = { {1d,0d,0d}, {0d,1d,0d}, {0d,0d,1d} }; - + // Test data for group operations protected double[][] testData = { {1d,2d,3d}, {2d,5d,3d}, {1d,0d,8d} }; protected double[][] testDataLU = {{2d, 5d, 3d}, {.5d, -2.5d, 6.5d}, {0.5d, 0.2d, .2d}}; protected double[][] testDataPlus2 = { {3d,4d,5d}, {4d,7d,5d}, {3d,2d,10d} }; - protected double[][] testDataMinus = { {-1d,-2d,-3d}, {-2d,-5d,-3d}, + protected double[][] testDataMinus = { {-1d,-2d,-3d}, {-2d,-5d,-3d}, {-1d,0d,-8d} }; protected double[] testDataRow1 = {1d,2d,3d}; protected double[] testDataCol3 = {3d,3d,8d}; - protected double[][] testDataInv = + protected double[][] testDataInv = { {-40d,16d,9d}, {13d,-5d,-3d}, {5d,-2d,-1d} }; protected double[] preMultTest = {8,12,33}; protected double[][] testData2 ={ {1d,2d,3d}, {2d,5d,3d}}; protected double[][] testData2T = { {1d,2d}, {2d,5d}, {3d,3d}}; - protected double[][] testDataPlusInv = + protected double[][] testDataPlusInv = { {-39d,18d,12d}, {15d,0d,0d}, {6d,-2d,7d} }; - + // lu decomposition tests protected double[][] luData = { {2d,3d,3d}, {0d,5d,7d}, {6d,9d,8d} }; protected double[][] luDataLUDecomposition = { {6d,9d,8d}, {0d,5d,7d}, {0.33333333333333,0d,0.33333333333333} }; - + // singular matrices protected double[][] singular = { {2d,3d}, {2d,3d} }; protected double[][] bigSingular = {{1d,2d,3d,4d}, {2d,5d,3d,4d}, {7d,3d,256d,1930d}, {3d,7d,6d,8d}}; // 4th row = 1st + 2nd protected double[][] detData = { {1d,2d,3d}, {4d,5d,6d}, {7d,8d,10d} }; protected double[][] detData2 = { {1d, 3d}, {2d, 4d}}; - + // vectors protected double[] testVector = {1,2,3}; protected double[] testVector2 = {1,2,3,4}; - + // submatrix accessor tests protected double[][] subTestData = {{1, 2, 3, 4}, {1.5, 2.5, 3.5, 4.5}, - {2, 4, 6, 8}, {4, 5, 6, 7}}; + {2, 4, 6, 8}, {4, 5, 6, 7}}; // array selections protected double[][] subRows02Cols13 = { {2, 4}, {4, 8}}; protected double[][] subRows03Cols12 = { {2, 3}, {5, 6}}; @@ -88,21 +88,21 @@ public final class BlockRealMatrixTest extends TestCase { // column matrices protected double[][] subColumn1 = {{2}, {2.5}, {4}, {5}}; protected double[][] subColumn3 = {{4}, {4.5}, {8}, {7}}; - + // tolerances protected double entryTolerance = 10E-16; protected double normTolerance = 10E-14; - + public BlockRealMatrixTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(BlockRealMatrixTest.class); suite.setName("BlockRealMatrix Tests"); return suite; } - + /** test dimensions */ public void testDimensions() { BlockRealMatrix m = new BlockRealMatrix(testData); @@ -113,8 +113,8 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals("testData2 row dimension",m2.getRowDimension(),2); assertEquals("testData2 column dimension",m2.getColumnDimension(),3); assertTrue("testData2 is not square",!m2.isSquare()); - } - + } + /** test copy functions */ public void testCopyFunctions() { Random r = new Random(66636328996002l); @@ -124,8 +124,8 @@ public final class BlockRealMatrixTest extends TestCase { BlockRealMatrix m3 = new BlockRealMatrix(testData); BlockRealMatrix m4 = new BlockRealMatrix(m3.getData()); assertEquals(m3, m4); - } - + } + /** test add */ public void testAdd() { BlockRealMatrix m = new BlockRealMatrix(testData); @@ -138,9 +138,9 @@ public final class BlockRealMatrixTest extends TestCase { testDataPlusInv[row][col],sumEntries[row][col], entryTolerance); } - } + } } - + /** test add failure */ public void testAddFail() { BlockRealMatrix m = new BlockRealMatrix(testData); @@ -152,7 +152,7 @@ public final class BlockRealMatrixTest extends TestCase { // ignored } } - + /** test norm */ public void testNorm() { BlockRealMatrix m = new BlockRealMatrix(testData); @@ -160,7 +160,7 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals("testData norm",14d,m.getNorm(),entryTolerance); assertEquals("testData2 norm",7d,m2.getNorm(),entryTolerance); } - + /** test Frobenius norm */ public void testFrobeniusNorm() { BlockRealMatrix m = new BlockRealMatrix(testData); @@ -168,20 +168,20 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals("testData Frobenius norm", Math.sqrt(117.0), m.getFrobeniusNorm(), entryTolerance); assertEquals("testData2 Frobenius norm", Math.sqrt(52.0), m2.getFrobeniusNorm(), entryTolerance); } - + /** test m-n = m + -n */ public void testPlusMinus() { BlockRealMatrix m = new BlockRealMatrix(testData); BlockRealMatrix m2 = new BlockRealMatrix(testDataInv); - assertClose(m.subtract(m2), m2.scalarMultiply(-1d).add(m), entryTolerance); + assertClose(m.subtract(m2), m2.scalarMultiply(-1d).add(m), entryTolerance); try { m.subtract(new BlockRealMatrix(testData2)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + /** test multiply */ public void testMultiply() { BlockRealMatrix m = new BlockRealMatrix(testData); @@ -192,13 +192,13 @@ public final class BlockRealMatrixTest extends TestCase { assertClose(mInv.multiply(m), identity, entryTolerance); assertClose(m.multiply(identity), m, entryTolerance); assertClose(identity.multiply(mInv), mInv, entryTolerance); - assertClose(m2.multiply(identity), m2, entryTolerance); + assertClose(m2.multiply(identity), m2, entryTolerance); try { m.multiply(new BlockRealMatrix(bigSingular)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } } public void testSeveralBlocks() { @@ -290,14 +290,14 @@ public final class BlockRealMatrixTest extends TestCase { private double[][] d3 = new double[][] {{1,2,3,4},{5,6,7,8}}; private double[][] d4 = new double[][] {{1},{2},{3},{4}}; private double[][] d5 = new double[][] {{30},{70}}; - - public void testMultiply2() { - RealMatrix m3 = new BlockRealMatrix(d3); + + public void testMultiply2() { + RealMatrix m3 = new BlockRealMatrix(d3); RealMatrix m4 = new BlockRealMatrix(d4); RealMatrix m5 = new BlockRealMatrix(d5); assertClose(m3.multiply(m4), m5, entryTolerance); - } - + } + /** test trace */ public void testTrace() { RealMatrix m = new BlockRealMatrix(id); @@ -308,15 +308,15 @@ public final class BlockRealMatrixTest extends TestCase { fail("Expecting NonSquareMatrixException"); } catch (NonSquareMatrixException ex) { // ignored - } + } } - + /** test scalarAdd */ public void testScalarAdd() { RealMatrix m = new BlockRealMatrix(testData); assertClose(new BlockRealMatrix(testDataPlus2), m.scalarAdd(2d), entryTolerance); } - + /** test operate */ public void testOperate() { RealMatrix m = new BlockRealMatrix(id); @@ -328,7 +328,7 @@ public final class BlockRealMatrixTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } public void testOperateLarge() { @@ -368,10 +368,10 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals( 7.0, b[1], 1.0e-12); assertEquals(11.0, b[2], 1.0e-12); } - + /** test transpose */ public void testTranspose() { - RealMatrix m = new BlockRealMatrix(testData); + RealMatrix m = new BlockRealMatrix(testData); RealMatrix mIT = new LUDecompositionImpl(m).getSolver().getInverse().transpose(); RealMatrix mTI = new LUDecompositionImpl(m.transpose()).getSolver().getInverse(); assertClose(mIT, mTI, normTolerance); @@ -379,7 +379,7 @@ public final class BlockRealMatrixTest extends TestCase { RealMatrix mt = new BlockRealMatrix(testData2T); assertClose(mt, m.transpose(), normTolerance); } - + /** test preMultiply by vector */ public void testPremultiplyVector() { RealMatrix m = new BlockRealMatrix(testData); @@ -394,13 +394,13 @@ public final class BlockRealMatrixTest extends TestCase { // ignored } } - + public void testPremultiply() { - RealMatrix m3 = new BlockRealMatrix(d3); + RealMatrix m3 = new BlockRealMatrix(d3); RealMatrix m4 = new BlockRealMatrix(d4); RealMatrix m5 = new BlockRealMatrix(d5); assertClose(m4.preMultiply(m3), m5, entryTolerance); - + BlockRealMatrix m = new BlockRealMatrix(testData); BlockRealMatrix mInv = new BlockRealMatrix(testDataInv); BlockRealMatrix identity = new BlockRealMatrix(id); @@ -413,9 +413,9 @@ public final class BlockRealMatrixTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + public void testGetVectors() { RealMatrix m = new BlockRealMatrix(testData); assertClose(m.getRow(0), testDataRow1, entryTolerance); @@ -433,7 +433,7 @@ public final class BlockRealMatrixTest extends TestCase { // ignored } } - + public void testGetEntry() { RealMatrix m = new BlockRealMatrix(testData); assertEquals("get entry",m.getEntry(0,1),2d,entryTolerance); @@ -444,7 +444,7 @@ public final class BlockRealMatrixTest extends TestCase { // expected } } - + /** test examples in user guide */ public void testExamples() { // Create a real matrix with two rows and three columns @@ -458,10 +458,10 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals(2, p.getRowDimension()); assertEquals(2, p.getColumnDimension()); // Invert p - RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse(); + RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse(); assertEquals(2, pInverse.getRowDimension()); assertEquals(2, pInverse.getColumnDimension()); - + // Solve example double[][] coefficientsData = {{2, 3, -2}, {-1, 7, 6}, {4, -3, -5}}; RealMatrix coefficients = new BlockRealMatrix(coefficientsData); @@ -469,22 +469,22 @@ public final class BlockRealMatrixTest extends TestCase { double[] solution = new LUDecompositionImpl(coefficients).getSolver().solve(constants); assertEquals(2 * solution[0] + 3 * solution[1] -2 * solution[2], constants[0], 1E-12); assertEquals(-1 * solution[0] + 7 * solution[1] + 6 * solution[2], constants[1], 1E-12); - assertEquals(4 * solution[0] - 3 * solution[1] -5 * solution[2], constants[2], 1E-12); - + assertEquals(4 * solution[0] - 3 * solution[1] -5 * solution[2], constants[2], 1E-12); + } - + // test submatrix accessors public void testGetSubMatrix() { RealMatrix m = new BlockRealMatrix(subTestData); checkGetSubMatrix(m, subRows23Cols00, 2 , 3 , 0, 0); checkGetSubMatrix(m, subRows00Cols33, 0 , 0 , 3, 3); - checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3); - checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); - checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); - checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); - checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3); + checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); + checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); + checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); + checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); checkGetSubMatrix(m, null, 1, 0, 2, 4); checkGetSubMatrix(m, null, -1, 1, 2, 2); checkGetSubMatrix(m, null, 1, 0, 2, 2); @@ -508,7 +508,7 @@ public final class BlockRealMatrixTest extends TestCase { } } } - + private void checkGetSubMatrix(RealMatrix m, double[][] reference, int[] selectedRows, int[] selectedColumns) { try { @@ -548,14 +548,14 @@ public final class BlockRealMatrixTest extends TestCase { RealMatrix m = new BlockRealMatrix(subTestData); checkCopy(m, subRows23Cols00, 2 , 3 , 0, 0); checkCopy(m, subRows00Cols33, 0 , 0 , 3, 3); - checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3); - checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); - checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); - checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); - checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - + checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3); + checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); + checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); + checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); + checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkCopy(m, null, 1, 0, 2, 4); checkCopy(m, null, -1, 1, 2, 2); checkCopy(m, null, 1, 0, 2, 2); @@ -582,7 +582,7 @@ public final class BlockRealMatrixTest extends TestCase { } } } - + private void checkCopy(RealMatrix m, double[][] reference, int[] selectedRows, int[] selectedColumns) { try { @@ -641,7 +641,7 @@ public final class BlockRealMatrixTest extends TestCase { // expected } } - + public void testGetSetRowMatrixLarge() { int n = 3 * BlockRealMatrix.BLOCK_SIZE; RealMatrix m = new BlockRealMatrix(n, n); @@ -660,7 +660,7 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals(sub, m.getRowMatrix(2)); } - + public void testGetColumnMatrix() { RealMatrix m = new BlockRealMatrix(subTestData); RealMatrix mColumn1 = new BlockRealMatrix(subColumn1); @@ -719,7 +719,7 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals(sub, m.getColumnMatrix(2)); } - + public void testGetRowVector() { RealMatrix m = new BlockRealMatrix(subTestData); RealVector mRow0 = new ArrayRealVector(subRow0[0]); @@ -778,7 +778,7 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals(sub, m.getRowVector(2)); } - + public void testGetColumnVector() { RealMatrix m = new BlockRealMatrix(subTestData); RealVector mColumn1 = columnToVector(subColumn1); @@ -837,7 +837,7 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals(sub, m.getColumnVector(2)); } - + private RealVector columnToVector(double[][] column) { double[] data = new double[column.length]; for (int i = 0; i < data.length; ++i) { @@ -902,7 +902,7 @@ public final class BlockRealMatrixTest extends TestCase { checkArrays(sub, m.getRow(2)); } - + public void testGetColumn() { RealMatrix m = new BlockRealMatrix(subTestData); double[] mColumn1 = columnToArray(subColumn1); @@ -962,7 +962,7 @@ public final class BlockRealMatrixTest extends TestCase { checkArrays(sub, m.getColumn(2)); } - + private double[] columnToArray(double[][] column) { double[] data = new double[column.length]; for (int i = 0; i < data.length; ++i) { @@ -974,10 +974,10 @@ public final class BlockRealMatrixTest extends TestCase { private void checkArrays(double[] expected, double[] actual) { assertEquals(expected.length, actual.length); for (int i = 0; i < expected.length; ++i) { - assertEquals(expected[i], actual[i]); + assertEquals(expected[i], actual[i]); } } - + public void testEqualsAndHashCode() { BlockRealMatrix m = new BlockRealMatrix(testData); BlockRealMatrix m1 = (BlockRealMatrix) m.copy(); @@ -988,61 +988,61 @@ public final class BlockRealMatrixTest extends TestCase { assertEquals(m, m1); assertFalse(m.equals(null)); assertFalse(m.equals(mt)); - assertFalse(m.equals(new BlockRealMatrix(bigSingular))); + assertFalse(m.equals(new BlockRealMatrix(bigSingular))); } - + public void testToString() { BlockRealMatrix m = new BlockRealMatrix(testData); assertEquals("BlockRealMatrix{{1.0,2.0,3.0},{2.0,5.0,3.0},{1.0,0.0,8.0}}", m.toString()); } - + public void testSetSubMatrix() throws Exception { BlockRealMatrix m = new BlockRealMatrix(testData); m.setSubMatrix(detData2,1,1); RealMatrix expected = new BlockRealMatrix (new double[][] {{1.0,2.0,3.0},{2.0,1.0,3.0},{1.0,2.0,4.0}}); - assertEquals(expected, m); - + assertEquals(expected, m); + m.setSubMatrix(detData2,0,0); expected = new BlockRealMatrix (new double[][] {{1.0,3.0,3.0},{2.0,4.0,3.0},{1.0,2.0,4.0}}); - assertEquals(expected, m); - - m.setSubMatrix(testDataPlus2,0,0); + assertEquals(expected, m); + + m.setSubMatrix(testDataPlus2,0,0); expected = new BlockRealMatrix (new double[][] {{3.0,4.0,5.0},{4.0,7.0,5.0},{3.0,2.0,10.0}}); - assertEquals(expected, m); - + assertEquals(expected, m); + // javadoc example BlockRealMatrix matrix = new BlockRealMatrix (new double[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1 , 2}}); matrix.setSubMatrix(new double[][] {{3, 4}, {5, 6}}, 1, 1); expected = new BlockRealMatrix (new double[][] {{1, 2, 3, 4}, {5, 3, 4, 8}, {9, 5 ,6, 2}}); - assertEquals(expected, matrix); + assertEquals(expected, matrix); // dimension overflow - try { + try { m.setSubMatrix(testData,1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } // dimension underflow - try { + try { m.setSubMatrix(testData,-1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - try { + try { m.setSubMatrix(testData,1,-1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - + // null try { m.setSubMatrix(null,1,1); @@ -1050,7 +1050,7 @@ public final class BlockRealMatrixTest extends TestCase { } catch (NullPointerException e) { // expected } - + // ragged try { m.setSubMatrix(new double[][] {{1}, {2, 3}}, 0, 0); @@ -1058,7 +1058,7 @@ public final class BlockRealMatrixTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + // empty try { m.setSubMatrix(new double[][] {{}}, 0, 0); @@ -1066,7 +1066,7 @@ public final class BlockRealMatrixTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + } public void testWalk() { @@ -1085,11 +1085,11 @@ public final class BlockRealMatrixTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -1105,11 +1105,11 @@ public final class BlockRealMatrixTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -1125,11 +1125,11 @@ public final class BlockRealMatrixTest extends TestCase { m.walkInRowOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -1145,16 +1145,16 @@ public final class BlockRealMatrixTest extends TestCase { m.walkInColumnOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } } - + public void testSerial() { BlockRealMatrix m = new BlockRealMatrix(testData); assertEquals(m,TestUtils.serializeAndRecover(m)); @@ -1180,12 +1180,12 @@ public final class BlockRealMatrixTest extends TestCase { } //--------------- -----------------Protected methods - - /** verifies that two matrices are close (1-norm) */ + + /** verifies that two matrices are close (1-norm) */ protected void assertClose(RealMatrix m, RealMatrix n, double tolerance) { assertTrue(m.subtract(n).getNorm() < tolerance); } - + /** verifies that two vectors are close (sup norm) */ protected void assertClose(double[] m, double[] n, double tolerance) { if (m.length != n.length) { @@ -1205,6 +1205,6 @@ public final class BlockRealMatrixTest extends TestCase { } return m; } - + } diff --git a/src/test/java/org/apache/commons/math/linear/CholeskyDecompositionImplTest.java b/src/test/java/org/apache/commons/math/linear/CholeskyDecompositionImplTest.java index 653ab5c8d..1b76eeac8 100644 --- a/src/test/java/org/apache/commons/math/linear/CholeskyDecompositionImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/CholeskyDecompositionImplTest.java @@ -84,7 +84,7 @@ public class CholeskyDecompositionImplTest { {-0.09376327, 0.10400408, 0.07137959, 0.04762857 }, { 0.30328980, 0.07137959, 0.30458776, 0.04882449 }, { 0.04909388, 0.04762857, 0.04882449, 0.07543265 } - + })); } @@ -144,7 +144,7 @@ public class CholeskyDecompositionImplTest { // check the same cached instance is returned the second time assertTrue(l == llt.getL()); assertTrue(lt == llt.getLT()); - + } } diff --git a/src/test/java/org/apache/commons/math/linear/EigenDecompositionImplTest.java b/src/test/java/org/apache/commons/math/linear/EigenDecompositionImplTest.java index 4a56dbad7..de595e5db 100644 --- a/src/test/java/org/apache/commons/math/linear/EigenDecompositionImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/EigenDecompositionImplTest.java @@ -116,7 +116,7 @@ public class EigenDecompositionImplTest extends TestCase { if (i < 5) { ref[i] = 2 * r.nextDouble() - 1; } else { - ref[i] = 0.0001 * r.nextDouble() + 6; + ref[i] = 0.0001 * r.nextDouble() + 6; } } Arrays.sort(ref); @@ -131,7 +131,7 @@ public class EigenDecompositionImplTest extends TestCase { for (int i = 0; i < ref.length; ++i) { assertEquals(ref[ref.length - i - 1], eigenValues[i], 2.0e-14); } - + } /** test dimensions */ @@ -221,19 +221,19 @@ public class EigenDecompositionImplTest extends TestCase { {3, 2, 4}, {2, 0, 2}, {4, 2, 3} - }); + }); EigenDecomposition ed = new EigenDecompositionImpl(repeated, MathUtils.SAFE_MIN); checkEigenValues((new double[] {8, -1, -1}), ed, 1E-12); checkEigenVector((new double[] {2, 1, 2}), ed, 1E-12); } - + /** * Matrix with eigenvalues {2, 0, 12} */ public void testDistinctEigenvalues() { RealMatrix distinct = MatrixUtils.createRealMatrix(new double[][] { - {3, 1, -4}, - {1, 3, -4}, + {3, 1, -4}, + {1, 3, -4}, {-4, -4, 8} }); EigenDecomposition ed = new EigenDecompositionImpl(distinct, MathUtils.SAFE_MIN); @@ -242,7 +242,7 @@ public class EigenDecompositionImplTest extends TestCase { checkEigenVector((new double[] {1, 1, 1}), ed, 1E-12); checkEigenVector((new double[] {-1, -1, 2}), ed, 1E-12); } - + /** * Verifies that the given EigenDecomposition has eigenvalues equivalent to * the targetValues, ignoring the order of the values and allowing @@ -256,7 +256,7 @@ public class EigenDecompositionImplTest extends TestCase { assertTrue(isIncludedValue(targetValues[i], observed, tolerance)); } } - + /** * Returns true iff there is an entry within tolerance of value in * searchArray. @@ -273,7 +273,7 @@ public class EigenDecompositionImplTest extends TestCase { } return found; } - + /** * Returns true iff eigenVector is a scalar multiple of one of the columns * of ed.getV(). Does not try linear combinations - i.e., should only be @@ -283,7 +283,7 @@ public class EigenDecompositionImplTest extends TestCase { EigenDecomposition ed, double tolerance) { assertTrue(isIncludedColumn(eigenVector, ed.getV(), tolerance)); } - + /** * Returns true iff there is a column that is a scalar multiple of column * in searchMatrix (modulo tolerance) @@ -302,7 +302,7 @@ public class EigenDecompositionImplTest extends TestCase { if (Math.abs(multiplier - 1.0) <= Math.ulp(1.0) && Math.abs(colEntry) > 1E-14 && Math.abs(column[j]) > 1e-14) { multiplier = colEntry / column[j]; - } + } if (Math.abs(column[j] * multiplier - colEntry) > tolerance) { matching = false; } diff --git a/src/test/java/org/apache/commons/math/linear/FieldLUDecompositionImplTest.java b/src/test/java/org/apache/commons/math/linear/FieldLUDecompositionImplTest.java index db21515e8..b4825479d 100644 --- a/src/test/java/org/apache/commons/math/linear/FieldLUDecompositionImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/FieldLUDecompositionImplTest.java @@ -46,7 +46,7 @@ public class FieldLUDecompositionImplTest extends TestCase { { new Fraction(2), new Fraction(3), new Fraction(7) }, { new Fraction(6), new Fraction(6), new Fraction(8) } }; - + // singular matrices private Fraction[][] singular = { { new Fraction(2), new Fraction(3) }, @@ -265,7 +265,7 @@ public class FieldLUDecompositionImplTest extends TestCase { assertTrue(l == lu.getL()); assertTrue(u == lu.getU()); assertTrue(p == lu.getP()); - + } /** test matrices values */ @@ -305,7 +305,7 @@ public class FieldLUDecompositionImplTest extends TestCase { assertTrue(l == lu.getL()); assertTrue(u == lu.getU()); assertTrue(p == lu.getP()); - + } } diff --git a/src/test/java/org/apache/commons/math/linear/FieldMatrixImplTest.java b/src/test/java/org/apache/commons/math/linear/FieldMatrixImplTest.java index bd48469eb..c2ad5c39c 100644 --- a/src/test/java/org/apache/commons/math/linear/FieldMatrixImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/FieldMatrixImplTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,45 +31,45 @@ import org.apache.commons.math.fraction.FractionField; */ public final class FieldMatrixImplTest extends TestCase { - + // 3 x 3 identity matrix protected Fraction[][] id = { {new Fraction(1),new Fraction(0),new Fraction(0)}, {new Fraction(0),new Fraction(1),new Fraction(0)}, {new Fraction(0),new Fraction(0),new Fraction(1)} }; - + // Test data for group operations protected Fraction[][] testData = { {new Fraction(1),new Fraction(2),new Fraction(3)}, {new Fraction(2),new Fraction(5),new Fraction(3)}, {new Fraction(1),new Fraction(0),new Fraction(8)} }; protected Fraction[][] testDataLU = {{new Fraction(2), new Fraction(5), new Fraction(3)}, {new Fraction(1, 2), new Fraction(-5, 2), new Fraction(13, 2)}, {new Fraction(1, 2), new Fraction(1, 5), new Fraction(1, 5)}}; protected Fraction[][] testDataPlus2 = { {new Fraction(3),new Fraction(4),new Fraction(5)}, {new Fraction(4),new Fraction(7),new Fraction(5)}, {new Fraction(3),new Fraction(2),new Fraction(10)} }; - protected Fraction[][] testDataMinus = { {new Fraction(-1),new Fraction(-2),new Fraction(-3)}, {new Fraction(-2),new Fraction(-5),new Fraction(-3)}, + protected Fraction[][] testDataMinus = { {new Fraction(-1),new Fraction(-2),new Fraction(-3)}, {new Fraction(-2),new Fraction(-5),new Fraction(-3)}, {new Fraction(-1),new Fraction(0),new Fraction(-8)} }; protected Fraction[] testDataRow1 = {new Fraction(1),new Fraction(2),new Fraction(3)}; protected Fraction[] testDataCol3 = {new Fraction(3),new Fraction(3),new Fraction(8)}; - protected Fraction[][] testDataInv = + protected Fraction[][] testDataInv = { {new Fraction(-40),new Fraction(16),new Fraction(9)}, {new Fraction(13),new Fraction(-5),new Fraction(-3)}, {new Fraction(5),new Fraction(-2),new Fraction(-1)} }; protected Fraction[] preMultTest = {new Fraction(8),new Fraction(12),new Fraction(33)}; protected Fraction[][] testData2 ={ {new Fraction(1),new Fraction(2),new Fraction(3)}, {new Fraction(2),new Fraction(5),new Fraction(3)}}; protected Fraction[][] testData2T = { {new Fraction(1),new Fraction(2)}, {new Fraction(2),new Fraction(5)}, {new Fraction(3),new Fraction(3)}}; - protected Fraction[][] testDataPlusInv = + protected Fraction[][] testDataPlusInv = { {new Fraction(-39),new Fraction(18),new Fraction(12)}, {new Fraction(15),new Fraction(0),new Fraction(0)}, {new Fraction(6),new Fraction(-2),new Fraction(7)} }; - + // lu decomposition tests protected Fraction[][] luData = { {new Fraction(2),new Fraction(3),new Fraction(3)}, {new Fraction(0),new Fraction(5),new Fraction(7)}, {new Fraction(6),new Fraction(9),new Fraction(8)} }; protected Fraction[][] luDataLUDecomposition = { {new Fraction(6),new Fraction(9),new Fraction(8)}, {new Fraction(0),new Fraction(5),new Fraction(7)}, {new Fraction(1, 3),new Fraction(0),new Fraction(1, 3)} }; - + // singular matrices protected Fraction[][] singular = { {new Fraction(2),new Fraction(3)}, {new Fraction(2),new Fraction(3)} }; protected Fraction[][] bigSingular = {{new Fraction(1),new Fraction(2),new Fraction(3),new Fraction(4)}, {new Fraction(2),new Fraction(5),new Fraction(3),new Fraction(4)}, {new Fraction(7),new Fraction(3),new Fraction(256),new Fraction(1930)}, {new Fraction(3),new Fraction(7),new Fraction(6),new Fraction(8)}}; // 4th row = 1st + 2nd protected Fraction[][] detData = { {new Fraction(1),new Fraction(2),new Fraction(3)}, {new Fraction(4),new Fraction(5),new Fraction(6)}, {new Fraction(7),new Fraction(8),new Fraction(10)} }; protected Fraction[][] detData2 = { {new Fraction(1), new Fraction(3)}, {new Fraction(2), new Fraction(4)}}; - + // vectors protected Fraction[] testVector = {new Fraction(1),new Fraction(2),new Fraction(3)}; protected Fraction[] testVector2 = {new Fraction(1),new Fraction(2),new Fraction(3),new Fraction(4)}; - + // submatrix accessor tests protected Fraction[][] subTestData = {{new Fraction(1), new Fraction(2), new Fraction(3), new Fraction(4)}, {new Fraction(3, 2), new Fraction(5, 2), new Fraction(7, 2), new Fraction(9, 2)}, - {new Fraction(2), new Fraction(4), new Fraction(6), new Fraction(8)}, {new Fraction(4), new Fraction(5), new Fraction(6), new Fraction(7)}}; + {new Fraction(2), new Fraction(4), new Fraction(6), new Fraction(8)}, {new Fraction(4), new Fraction(5), new Fraction(6), new Fraction(7)}}; // array selections protected Fraction[][] subRows02Cols13 = { {new Fraction(2), new Fraction(4)}, {new Fraction(4), new Fraction(8)}}; protected Fraction[][] subRows03Cols12 = { {new Fraction(2), new Fraction(3)}, {new Fraction(5), new Fraction(6)}}; @@ -87,21 +87,21 @@ public final class FieldMatrixImplTest extends TestCase { // column matrices protected Fraction[][] subColumn1 = {{new Fraction(2)}, {new Fraction(5, 2)}, {new Fraction(4)}, {new Fraction(5)}}; protected Fraction[][] subColumn3 = {{new Fraction(4)}, {new Fraction(9, 2)}, {new Fraction(8)}, {new Fraction(7)}}; - + // tolerances protected double entryTolerance = 10E-16; protected double normTolerance = 10E-14; - + public FieldMatrixImplTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(FieldMatrixImplTest.class); suite.setName("Array2DRowFieldMatrix Tests"); return suite; } - + /** test dimensions */ public void testDimensions() { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); @@ -112,8 +112,8 @@ public final class FieldMatrixImplTest extends TestCase { assertEquals("testData2 row dimension",m2.getRowDimension(),2); assertEquals("testData2 column dimension",m2.getColumnDimension(),3); assertTrue("testData2 is not square",!m2.isSquare()); - } - + } + /** test copy functions */ public void testCopyFunctions() { Array2DRowFieldMatrix m1 = new Array2DRowFieldMatrix(testData); @@ -122,8 +122,8 @@ public final class FieldMatrixImplTest extends TestCase { Array2DRowFieldMatrix m3 = new Array2DRowFieldMatrix(testData); Array2DRowFieldMatrix m4 = new Array2DRowFieldMatrix(m3.getData(), false); assertEquals(m4,m3); - } - + } + /** test add */ public void testAdd() { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); @@ -134,9 +134,9 @@ public final class FieldMatrixImplTest extends TestCase { for (int col = 0; col < m.getColumnDimension(); col++) { assertEquals(testDataPlusInv[row][col],sumEntries[row][col]); } - } + } } - + /** test add failure */ public void testAddFail() { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); @@ -148,20 +148,20 @@ public final class FieldMatrixImplTest extends TestCase { // ignored } } - + /** test m-n = m + -n */ public void testPlusMinus() { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); Array2DRowFieldMatrix m2 = new Array2DRowFieldMatrix(testDataInv); - TestUtils.assertEquals(m.subtract(m2),m2.scalarMultiply(new Fraction(-1)).add(m)); + TestUtils.assertEquals(m.subtract(m2),m2.scalarMultiply(new Fraction(-1)).add(m)); try { m.subtract(new Array2DRowFieldMatrix(testData2)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + /** test multiply */ public void testMultiply() { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); @@ -172,28 +172,28 @@ public final class FieldMatrixImplTest extends TestCase { TestUtils.assertEquals(mInv.multiply(m), identity); TestUtils.assertEquals(m.multiply(identity), m); TestUtils.assertEquals(identity.multiply(mInv), mInv); - TestUtils.assertEquals(m2.multiply(identity), m2); + TestUtils.assertEquals(m2.multiply(identity), m2); try { m.multiply(new Array2DRowFieldMatrix(bigSingular)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } - } - + } + } + //Additional Test for Array2DRowFieldMatrixTest.testMultiply private Fraction[][] d3 = new Fraction[][] {{new Fraction(1),new Fraction(2),new Fraction(3),new Fraction(4)},{new Fraction(5),new Fraction(6),new Fraction(7),new Fraction(8)}}; private Fraction[][] d4 = new Fraction[][] {{new Fraction(1)},{new Fraction(2)},{new Fraction(3)},{new Fraction(4)}}; private Fraction[][] d5 = new Fraction[][] {{new Fraction(30)},{new Fraction(70)}}; - - public void testMultiply2() { - FieldMatrix m3 = new Array2DRowFieldMatrix(d3); + + public void testMultiply2() { + FieldMatrix m3 = new Array2DRowFieldMatrix(d3); FieldMatrix m4 = new Array2DRowFieldMatrix(d4); FieldMatrix m5 = new Array2DRowFieldMatrix(d5); TestUtils.assertEquals(m3.multiply(m4), m5); - } - + } + /** test trace */ public void testTrace() { FieldMatrix m = new Array2DRowFieldMatrix(id); @@ -204,15 +204,15 @@ public final class FieldMatrixImplTest extends TestCase { fail("Expecting NonSquareMatrixException"); } catch (NonSquareMatrixException ex) { // ignored - } + } } - + /** test sclarAdd */ public void testScalarAdd() { FieldMatrix m = new Array2DRowFieldMatrix(testData); TestUtils.assertEquals(new Array2DRowFieldMatrix(testDataPlus2), m.scalarAdd(new Fraction(2))); } - + /** test operate */ public void testOperate() { FieldMatrix m = new Array2DRowFieldMatrix(id); @@ -224,7 +224,7 @@ public final class FieldMatrixImplTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } /** test issue MATH-209 */ @@ -238,10 +238,10 @@ public final class FieldMatrixImplTest extends TestCase { assertEquals( new Fraction(7), b[1]); assertEquals(new Fraction(11), b[2]); } - + /** test transpose */ public void testTranspose() { - FieldMatrix m = new Array2DRowFieldMatrix(testData); + FieldMatrix m = new Array2DRowFieldMatrix(testData); FieldMatrix mIT = new FieldLUDecompositionImpl(m).getSolver().getInverse().transpose(); FieldMatrix mTI = new FieldLUDecompositionImpl(m.transpose()).getSolver().getInverse(); TestUtils.assertEquals(mIT, mTI); @@ -249,7 +249,7 @@ public final class FieldMatrixImplTest extends TestCase { FieldMatrix mt = new Array2DRowFieldMatrix(testData2T); TestUtils.assertEquals(mt, m.transpose()); } - + /** test preMultiply by vector */ public void testPremultiplyVector() { FieldMatrix m = new Array2DRowFieldMatrix(testData); @@ -264,13 +264,13 @@ public final class FieldMatrixImplTest extends TestCase { // ignored } } - + public void testPremultiply() { - FieldMatrix m3 = new Array2DRowFieldMatrix(d3); + FieldMatrix m3 = new Array2DRowFieldMatrix(d3); FieldMatrix m4 = new Array2DRowFieldMatrix(d4); FieldMatrix m5 = new Array2DRowFieldMatrix(d5); TestUtils.assertEquals(m4.preMultiply(m3), m5); - + Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); Array2DRowFieldMatrix mInv = new Array2DRowFieldMatrix(testDataInv); Array2DRowFieldMatrix identity = new Array2DRowFieldMatrix(id); @@ -283,9 +283,9 @@ public final class FieldMatrixImplTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + public void testGetVectors() { FieldMatrix m = new Array2DRowFieldMatrix(testData); TestUtils.assertEquals(m.getRow(0), testDataRow1); @@ -303,7 +303,7 @@ public final class FieldMatrixImplTest extends TestCase { // ignored } } - + public void testGetEntry() { FieldMatrix m = new Array2DRowFieldMatrix(testData); assertEquals("get entry",m.getEntry(0,1),new Fraction(2)); @@ -314,7 +314,7 @@ public final class FieldMatrixImplTest extends TestCase { // expected } } - + /** test examples in user guide */ public void testExamples() { // Create a real matrix with two rows and three columns @@ -335,10 +335,10 @@ public final class FieldMatrixImplTest extends TestCase { assertEquals(2, p.getRowDimension()); assertEquals(2, p.getColumnDimension()); // Invert p - FieldMatrix pInverse = new FieldLUDecompositionImpl(p).getSolver().getInverse(); + FieldMatrix pInverse = new FieldLUDecompositionImpl(p).getSolver().getInverse(); assertEquals(2, pInverse.getRowDimension()); assertEquals(2, pInverse.getColumnDimension()); - + // Solve example Fraction[][] coefficientsData = { {new Fraction(2), new Fraction(3), new Fraction(-2)}, @@ -356,22 +356,22 @@ public final class FieldMatrixImplTest extends TestCase { add(new Fraction(6).multiply(solution[2])), constants[1]); assertEquals(new Fraction(4).multiply(solution[0]). subtract(new Fraction(3).multiply(solution[1])). - subtract(new Fraction(5).multiply(solution[2])), constants[2]); - + subtract(new Fraction(5).multiply(solution[2])), constants[2]); + } - + // test submatrix accessors public void testGetSubMatrix() { FieldMatrix m = new Array2DRowFieldMatrix(subTestData); checkGetSubMatrix(m, subRows23Cols00, 2 , 3 , 0, 0); checkGetSubMatrix(m, subRows00Cols33, 0 , 0 , 3, 3); - checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3); - checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); - checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); - checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); - checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3); + checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); + checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); + checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); + checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); checkGetSubMatrix(m, null, 1, 0, 2, 4); checkGetSubMatrix(m, null, -1, 1, 2, 2); checkGetSubMatrix(m, null, 1, 0, 2, 2); @@ -395,7 +395,7 @@ public final class FieldMatrixImplTest extends TestCase { } } } - + private void checkGetSubMatrix(FieldMatrix m, Fraction[][] reference, int[] selectedRows, int[] selectedColumns) { try { @@ -416,14 +416,14 @@ public final class FieldMatrixImplTest extends TestCase { FieldMatrix m = new Array2DRowFieldMatrix(subTestData); checkCopy(m, subRows23Cols00, 2 , 3 , 0, 0); checkCopy(m, subRows00Cols33, 0 , 0 , 3, 3); - checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3); - checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); - checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); - checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); - checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); - + checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3); + checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }); + checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }); + checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }); + checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }); + checkCopy(m, null, 1, 0, 2, 4); checkCopy(m, null, -1, 1, 2, 2); checkCopy(m, null, 1, 0, 2, 2); @@ -450,7 +450,7 @@ public final class FieldMatrixImplTest extends TestCase { } } } - + private void checkCopy(FieldMatrix m, Fraction[][] reference, int[] selectedRows, int[] selectedColumns) { try { @@ -474,9 +474,9 @@ public final class FieldMatrixImplTest extends TestCase { FieldMatrix m = new Array2DRowFieldMatrix(subTestData); FieldMatrix mRow0 = new Array2DRowFieldMatrix(subRow0); FieldMatrix mRow3 = new Array2DRowFieldMatrix(subRow3); - assertEquals("Row0", mRow0, + assertEquals("Row0", mRow0, m.getRowMatrix(0)); - assertEquals("Row3", mRow3, + assertEquals("Row3", mRow3, m.getRowMatrix(3)); try { m.getRowMatrix(-1); @@ -491,7 +491,7 @@ public final class FieldMatrixImplTest extends TestCase { // expected } } - + public void testSetRowMatrix() { FieldMatrix m = new Array2DRowFieldMatrix(subTestData); FieldMatrix mRow3 = new Array2DRowFieldMatrix(subRow3); @@ -511,14 +511,14 @@ public final class FieldMatrixImplTest extends TestCase { // expected } } - + public void testGetColumnMatrix() { FieldMatrix m = new Array2DRowFieldMatrix(subTestData); FieldMatrix mColumn1 = new Array2DRowFieldMatrix(subColumn1); FieldMatrix mColumn3 = new Array2DRowFieldMatrix(subColumn3); - assertEquals("Column1", mColumn1, + assertEquals("Column1", mColumn1, m.getColumnMatrix(1)); - assertEquals("Column3", mColumn3, + assertEquals("Column3", mColumn3, m.getColumnMatrix(3)); try { m.getColumnMatrix(-1); @@ -593,7 +593,7 @@ public final class FieldMatrixImplTest extends TestCase { // expected } } - + public void testGetColumnVector() { FieldMatrix m = new Array2DRowFieldMatrix(subTestData); FieldVector mColumn1 = columnToVector(subColumn1); @@ -678,7 +678,7 @@ public final class FieldMatrixImplTest extends TestCase { // expected } } - + public void testGetColumn() { FieldMatrix m = new Array2DRowFieldMatrix(subTestData); Fraction[] mColumn1 = columnToArray(subColumn1); @@ -730,10 +730,10 @@ public final class FieldMatrixImplTest extends TestCase { private void checkArrays(Fraction[] expected, Fraction[] actual) { assertEquals(expected.length, actual.length); for (int i = 0; i < expected.length; ++i) { - assertEquals(expected[i], actual[i]); + assertEquals(expected[i], actual[i]); } } - + public void testEqualsAndHashCode() { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); Array2DRowFieldMatrix m1 = (Array2DRowFieldMatrix) m.copy(); @@ -744,16 +744,16 @@ public final class FieldMatrixImplTest extends TestCase { assertEquals(m, m1); assertFalse(m.equals(null)); assertFalse(m.equals(mt)); - assertFalse(m.equals(new Array2DRowFieldMatrix(bigSingular))); + assertFalse(m.equals(new Array2DRowFieldMatrix(bigSingular))); } - + public void testToString() { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); assertEquals("Array2DRowFieldMatrix{{1,2,3},{2,5,3},{1,0,8}}", m.toString()); m = new Array2DRowFieldMatrix(FractionField.getInstance()); assertEquals("Array2DRowFieldMatrix{}", m.toString()); } - + public void testSetSubMatrix() throws Exception { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); m.setSubMatrix(detData2,1,1); @@ -763,8 +763,8 @@ public final class FieldMatrixImplTest extends TestCase { {new Fraction(2),new Fraction(1),new Fraction(3)}, {new Fraction(1),new Fraction(2),new Fraction(4)} }); - assertEquals(expected, m); - + assertEquals(expected, m); + m.setSubMatrix(detData2,0,0); expected = new Array2DRowFieldMatrix (new Fraction[][] { @@ -772,38 +772,38 @@ public final class FieldMatrixImplTest extends TestCase { {new Fraction(2),new Fraction(4),new Fraction(3)}, {new Fraction(1),new Fraction(2),new Fraction(4)} }); - assertEquals(expected, m); - - m.setSubMatrix(testDataPlus2,0,0); + assertEquals(expected, m); + + m.setSubMatrix(testDataPlus2,0,0); expected = new Array2DRowFieldMatrix (new Fraction[][] { {new Fraction(3),new Fraction(4),new Fraction(5)}, {new Fraction(4),new Fraction(7),new Fraction(5)}, {new Fraction(3),new Fraction(2),new Fraction(10)} }); - assertEquals(expected, m); - + assertEquals(expected, m); + // dimension overflow - try { + try { m.setSubMatrix(testData,1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } // dimension underflow - try { + try { m.setSubMatrix(testData,-1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - try { + try { m.setSubMatrix(testData,1,-1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - + // null try { m.setSubMatrix(null,1,1); @@ -824,7 +824,7 @@ public final class FieldMatrixImplTest extends TestCase { } catch (IllegalStateException e) { // expected } - + // ragged try { m.setSubMatrix(new Fraction[][] {{new Fraction(1)}, {new Fraction(2), new Fraction(3)}}, 0, 0); @@ -832,7 +832,7 @@ public final class FieldMatrixImplTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + // empty try { m.setSubMatrix(new Fraction[][] {{}}, 0, 0); @@ -840,7 +840,7 @@ public final class FieldMatrixImplTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + } public void testWalk() { @@ -860,11 +860,11 @@ public final class FieldMatrixImplTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(new Fraction(0), m.getEntry(i, 0)); + assertEquals(new Fraction(0), m.getEntry(i, 0)); assertEquals(new Fraction(0), m.getEntry(i, columns - 1)); } for (int j = 0; j < columns; ++j) { - assertEquals(new Fraction(0), m.getEntry(0, j)); + assertEquals(new Fraction(0), m.getEntry(0, j)); assertEquals(new Fraction(0), m.getEntry(rows - 1, j)); } @@ -880,11 +880,11 @@ public final class FieldMatrixImplTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(new Fraction(0), m.getEntry(i, 0)); + assertEquals(new Fraction(0), m.getEntry(i, 0)); assertEquals(new Fraction(0), m.getEntry(i, columns - 1)); } for (int j = 0; j < columns; ++j) { - assertEquals(new Fraction(0), m.getEntry(0, j)); + assertEquals(new Fraction(0), m.getEntry(0, j)); assertEquals(new Fraction(0), m.getEntry(rows - 1, j)); } @@ -900,11 +900,11 @@ public final class FieldMatrixImplTest extends TestCase { m.walkInRowOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(new Fraction(0), m.getEntry(i, 0)); + assertEquals(new Fraction(0), m.getEntry(i, 0)); assertEquals(new Fraction(0), m.getEntry(i, columns - 1)); } for (int j = 0; j < columns; ++j) { - assertEquals(new Fraction(0), m.getEntry(0, j)); + assertEquals(new Fraction(0), m.getEntry(0, j)); assertEquals(new Fraction(0), m.getEntry(rows - 1, j)); } @@ -920,11 +920,11 @@ public final class FieldMatrixImplTest extends TestCase { m.walkInColumnOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(new Fraction(0), m.getEntry(i, 0)); + assertEquals(new Fraction(0), m.getEntry(i, 0)); assertEquals(new Fraction(0), m.getEntry(i, columns - 1)); } for (int j = 0; j < columns; ++j) { - assertEquals(new Fraction(0), m.getEntry(0, j)); + assertEquals(new Fraction(0), m.getEntry(0, j)); assertEquals(new Fraction(0), m.getEntry(rows - 1, j)); } @@ -934,7 +934,7 @@ public final class FieldMatrixImplTest extends TestCase { Array2DRowFieldMatrix m = new Array2DRowFieldMatrix(testData); assertEquals(m,TestUtils.serializeAndRecover(m)); } - + private static class SetVisitor extends DefaultFieldMatrixChangingVisitor { public SetVisitor() { super(Fraction.ZERO); @@ -962,19 +962,19 @@ public final class FieldMatrixImplTest extends TestCase { } //--------------- -----------------Protected methods - + /** extracts the l and u matrices from compact lu representation */ protected void splitLU(FieldMatrix lu, Fraction[][] lowerData, Fraction[][] upperData) - throws InvalidMatrixException { + throws InvalidMatrixException { if (!lu.isSquare() || lowerData.length != lowerData[0].length || upperData.length != upperData[0].length || lowerData.length != upperData.length || lowerData.length != lu.getRowDimension()) { throw new InvalidMatrixException("incorrect dimensions"); - } + } int n = lu.getRowDimension(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { @@ -987,11 +987,11 @@ public final class FieldMatrixImplTest extends TestCase { } else { lowerData[i][j] = Fraction.ZERO; upperData[i][j] = lu.getEntry(i, j); - } + } } } } - + /** Returns the result of applying the given row permutation to the matrix */ protected FieldMatrix permuteRows(FieldMatrix matrix, int[] permutation) { if (!matrix.isSquare() || matrix.getRowDimension() != permutation.length) { @@ -1007,6 +1007,6 @@ public final class FieldMatrixImplTest extends TestCase { } return new Array2DRowFieldMatrix(out); } - + } diff --git a/src/test/java/org/apache/commons/math/linear/FrenchRealVectorFormatTest.java b/src/test/java/org/apache/commons/math/linear/FrenchRealVectorFormatTest.java index 1df03d8d4..59d988007 100644 --- a/src/test/java/org/apache/commons/math/linear/FrenchRealVectorFormatTest.java +++ b/src/test/java/org/apache/commons/math/linear/FrenchRealVectorFormatTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/test/java/org/apache/commons/math/linear/InvalidMatrixExceptionTest.java b/src/test/java/org/apache/commons/math/linear/InvalidMatrixExceptionTest.java index 9c690bab8..33ff4655b 100644 --- a/src/test/java/org/apache/commons/math/linear/InvalidMatrixExceptionTest.java +++ b/src/test/java/org/apache/commons/math/linear/InvalidMatrixExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,7 +23,7 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class InvalidMatrixExceptionTest extends TestCase { - + public void testConstructorMessage(){ String msg = "message"; InvalidMatrixException ex = new InvalidMatrixException(msg); diff --git a/src/test/java/org/apache/commons/math/linear/LUDecompositionImplTest.java b/src/test/java/org/apache/commons/math/linear/LUDecompositionImplTest.java index 6f776cdff..9bcab252e 100644 --- a/src/test/java/org/apache/commons/math/linear/LUDecompositionImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/LUDecompositionImplTest.java @@ -43,7 +43,7 @@ public class LUDecompositionImplTest extends TestCase { { 0.0, 5.0, 7.0 }, { 6.0, 9.0, 8.0 } }; - + // singular matrices private double[][] singular = { { 2.0, 3.0 }, @@ -257,7 +257,7 @@ public class LUDecompositionImplTest extends TestCase { assertTrue(l == lu.getL()); assertTrue(u == lu.getU()); assertTrue(p == lu.getP()); - + } /** test matrices values */ @@ -297,7 +297,7 @@ public class LUDecompositionImplTest extends TestCase { assertTrue(l == lu.getL()); assertTrue(u == lu.getU()); assertTrue(p == lu.getP()); - + } } diff --git a/src/test/java/org/apache/commons/math/linear/LUSolverTest.java b/src/test/java/org/apache/commons/math/linear/LUSolverTest.java index 09587ef68..d63378530 100644 --- a/src/test/java/org/apache/commons/math/linear/LUSolverTest.java +++ b/src/test/java/org/apache/commons/math/linear/LUSolverTest.java @@ -39,7 +39,7 @@ public class LUSolverTest extends TestCase { { 0.0, 5.0, 7.0 }, { 6.0, 9.0, 8.0 } }; - + // singular matrices private double[][] singular = { { 2.0, 3.0 }, diff --git a/src/test/java/org/apache/commons/math/linear/MatrixIndexExceptionTest.java b/src/test/java/org/apache/commons/math/linear/MatrixIndexExceptionTest.java index 30ff07cae..37e5fd485 100644 --- a/src/test/java/org/apache/commons/math/linear/MatrixIndexExceptionTest.java +++ b/src/test/java/org/apache/commons/math/linear/MatrixIndexExceptionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,9 +23,9 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class MatrixIndexExceptionTest extends TestCase { - + /** - * + * */ public void testConstructorMessage(){ String msg = "message"; diff --git a/src/test/java/org/apache/commons/math/linear/MatrixUtilsTest.java b/src/test/java/org/apache/commons/math/linear/MatrixUtilsTest.java index 13c408451..7130df483 100644 --- a/src/test/java/org/apache/commons/math/linear/MatrixUtilsTest.java +++ b/src/test/java/org/apache/commons/math/linear/MatrixUtilsTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,55 +33,55 @@ import org.apache.commons.math.fraction.FractionField; */ public final class MatrixUtilsTest extends TestCase { - + protected double[][] testData = { {1d,2d,3d}, {2d,5d,3d}, {1d,0d,8d} }; protected double[][] nullMatrix = null; protected double[] row = {1,2,3}; - protected BigDecimal[] bigRow = + protected BigDecimal[] bigRow = {new BigDecimal(1),new BigDecimal(2),new BigDecimal(3)}; protected String[] stringRow = {"1", "2", "3"}; - protected Fraction[] fractionRow = + protected Fraction[] fractionRow = {new Fraction(1),new Fraction(2),new Fraction(3)}; protected double[][] rowMatrix = {{1,2,3}}; - protected BigDecimal[][] bigRowMatrix = + protected BigDecimal[][] bigRowMatrix = {{new BigDecimal(1), new BigDecimal(2), new BigDecimal(3)}}; protected String[][] stringRowMatrix = {{"1", "2", "3"}}; - protected Fraction[][] fractionRowMatrix = + protected Fraction[][] fractionRowMatrix = {{new Fraction(1), new Fraction(2), new Fraction(3)}}; protected double[] col = {0,4,6}; - protected BigDecimal[] bigCol = + protected BigDecimal[] bigCol = {new BigDecimal(0),new BigDecimal(4),new BigDecimal(6)}; protected String[] stringCol = {"0","4","6"}; - protected Fraction[] fractionCol = + protected Fraction[] fractionCol = {new Fraction(0),new Fraction(4),new Fraction(6)}; protected double[] nullDoubleArray = null; protected double[][] colMatrix = {{0},{4},{6}}; - protected BigDecimal[][] bigColMatrix = + protected BigDecimal[][] bigColMatrix = {{new BigDecimal(0)},{new BigDecimal(4)},{new BigDecimal(6)}}; protected String[][] stringColMatrix = {{"0"}, {"4"}, {"6"}}; - protected Fraction[][] fractionColMatrix = + protected Fraction[][] fractionColMatrix = {{new Fraction(0)},{new Fraction(4)},{new Fraction(6)}}; - + public MatrixUtilsTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(MatrixUtilsTest.class); suite.setName("MatrixUtils Tests"); return suite; } - + public void testCreateRealMatrix() { - assertEquals(new BlockRealMatrix(testData), + assertEquals(new BlockRealMatrix(testData), MatrixUtils.createRealMatrix(testData)); try { MatrixUtils.createRealMatrix(new double[][] {{1}, {1,2}}); // ragged fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } try { MatrixUtils.createRealMatrix(new double[][] {{}, {}}); // no columns fail("Expecting IllegalArgumentException"); @@ -93,20 +93,20 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } public void testcreateFieldMatrix() { - assertEquals(new Array2DRowFieldMatrix(asFraction(testData)), + assertEquals(new Array2DRowFieldMatrix(asFraction(testData)), MatrixUtils.createFieldMatrix(asFraction(testData))); - assertEquals(new Array2DRowFieldMatrix(fractionColMatrix), + assertEquals(new Array2DRowFieldMatrix(fractionColMatrix), MatrixUtils.createFieldMatrix(fractionColMatrix)); try { MatrixUtils.createFieldMatrix(asFraction(new double[][] {{1}, {1,2}})); // ragged fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } try { MatrixUtils.createFieldMatrix(asFraction(new double[][] {{}, {}})); // no columns fail("Expecting IllegalArgumentException"); @@ -118,27 +118,27 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } @Deprecated public void testCreateBigMatrix() { - assertEquals(new BigMatrixImpl(testData), + assertEquals(new BigMatrixImpl(testData), MatrixUtils.createBigMatrix(testData)); - assertEquals(new BigMatrixImpl(BigMatrixImplTest.asBigDecimal(testData), true), + assertEquals(new BigMatrixImpl(BigMatrixImplTest.asBigDecimal(testData), true), MatrixUtils.createBigMatrix(BigMatrixImplTest.asBigDecimal(testData), false)); - assertEquals(new BigMatrixImpl(BigMatrixImplTest.asBigDecimal(testData), false), + assertEquals(new BigMatrixImpl(BigMatrixImplTest.asBigDecimal(testData), false), MatrixUtils.createBigMatrix(BigMatrixImplTest.asBigDecimal(testData), true)); - assertEquals(new BigMatrixImpl(bigColMatrix), + assertEquals(new BigMatrixImpl(bigColMatrix), MatrixUtils.createBigMatrix(bigColMatrix)); - assertEquals(new BigMatrixImpl(stringColMatrix), + assertEquals(new BigMatrixImpl(stringColMatrix), MatrixUtils.createBigMatrix(stringColMatrix)); try { MatrixUtils.createBigMatrix(new double[][] {{1}, {1,2}}); // ragged fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } try { MatrixUtils.createBigMatrix(new double[][] {{}, {}}); // no columns fail("Expecting IllegalArgumentException"); @@ -150,9 +150,9 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } - + public void testCreateRowRealMatrix() { assertEquals(MatrixUtils.createRowRealMatrix(row), new BlockRealMatrix(rowMatrix)); @@ -167,9 +167,9 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } - + public void testCreateRowFieldMatrix() { assertEquals(MatrixUtils.createRowFieldMatrix(asFraction(row)), new Array2DRowFieldMatrix(asFraction(rowMatrix))); @@ -186,7 +186,7 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } @Deprecated @@ -208,7 +208,7 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } public void testCreateColumnRealMatrix() { @@ -225,9 +225,9 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } - + public void testCreateColumnFieldMatrix() { assertEquals(MatrixUtils.createColumnFieldMatrix(asFraction(col)), new Array2DRowFieldMatrix(asFraction(colMatrix))); @@ -245,7 +245,7 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } @Deprecated @@ -255,8 +255,8 @@ public final class MatrixUtilsTest extends TestCase { assertEquals(MatrixUtils.createColumnBigMatrix(bigCol), new BigMatrixImpl(bigColMatrix)); assertEquals(MatrixUtils.createColumnBigMatrix(stringCol), - new BigMatrixImpl(stringColMatrix)); - + new BigMatrixImpl(stringColMatrix)); + try { MatrixUtils.createColumnBigMatrix(new double[] {}); // empty fail("Expecting IllegalArgumentException"); @@ -268,7 +268,7 @@ public final class MatrixUtilsTest extends TestCase { fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected - } + } } /** @@ -283,9 +283,9 @@ public final class MatrixUtilsTest extends TestCase { assertEquals(m.getEntry(i, j), 0d, 0); } } - } + } } - + public void testCreateIdentityMatrix() { checkIdentityMatrix(MatrixUtils.createRealIdentityMatrix(3)); checkIdentityMatrix(MatrixUtils.createRealIdentityMatrix(2)); @@ -296,7 +296,7 @@ public final class MatrixUtilsTest extends TestCase { // expected } } - + /** * Verifies that the matrix is an identity matrix */ @@ -309,9 +309,9 @@ public final class MatrixUtilsTest extends TestCase { assertEquals(m.getEntry(i, j), Fraction.ZERO); } } - } + } } - + public void testcreateFieldIdentityMatrix() { checkIdentityFieldMatrix(MatrixUtils.createFieldIdentityMatrix(FractionField.getInstance(), 3)); checkIdentityFieldMatrix(MatrixUtils.createFieldIdentityMatrix(FractionField.getInstance(), 2)); @@ -389,7 +389,7 @@ public final class MatrixUtilsTest extends TestCase { assertEquals(m.getEntry(i, j), BigMatrixImpl.ZERO); } } - } + } } @Deprecated diff --git a/src/test/java/org/apache/commons/math/linear/QRDecompositionImplTest.java b/src/test/java/org/apache/commons/math/linear/QRDecompositionImplTest.java index ebda5960a..8f146451f 100644 --- a/src/test/java/org/apache/commons/math/linear/QRDecompositionImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/QRDecompositionImplTest.java @@ -33,25 +33,25 @@ import junit.framework.TestCase; import junit.framework.TestSuite; public class QRDecompositionImplTest extends TestCase { - double[][] testData3x3NonSingular = { - { 12, -51, 4 }, + double[][] testData3x3NonSingular = { + { 12, -51, 4 }, { 6, 167, -68 }, { -4, 24, -41 }, }; - double[][] testData3x3Singular = { - { 1, 4, 7, }, + double[][] testData3x3Singular = { + { 1, 4, 7, }, { 2, 5, 8, }, { 3, 6, 9, }, }; - double[][] testData3x4 = { - { 12, -51, 4, 1 }, + double[][] testData3x4 = { + { 12, -51, 4, 1 }, { 6, 167, -68, 2 }, { -4, 24, -41, 3 }, }; - double[][] testData4x3 = { - { 12, -51, 4, }, + double[][] testData4x3 = { + { 12, -51, 4, }, { 6, 167, -68, }, - { -4, 24, -41, }, + { -4, 24, -41, }, { -5, 34, 7, }, }; private static final double entryTolerance = 10e-16; @@ -91,7 +91,7 @@ public class QRDecompositionImplTest extends TestCase { assertEquals(rows, qr.getQ().getRowDimension()); assertEquals(rows, qr.getQ().getColumnDimension()); assertEquals(rows, qr.getR().getRowDimension()); - assertEquals(columns, qr.getR().getColumnDimension()); + assertEquals(columns, qr.getR().getColumnDimension()); } /** test A = QR */ @@ -250,7 +250,7 @@ public class QRDecompositionImplTest extends TestCase { assertTrue(q == qr.getQ()); assertTrue(r == qr.getR()); assertTrue(h == qr.getH()); - + } private RealMatrix createTestMatrix(final Random r, final int rows, final int columns) { diff --git a/src/test/java/org/apache/commons/math/linear/QRSolverTest.java b/src/test/java/org/apache/commons/math/linear/QRSolverTest.java index 9db148207..76645ecdd 100644 --- a/src/test/java/org/apache/commons/math/linear/QRSolverTest.java +++ b/src/test/java/org/apache/commons/math/linear/QRSolverTest.java @@ -36,28 +36,28 @@ import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.linear.ArrayRealVector; public class QRSolverTest extends TestCase { - double[][] testData3x3NonSingular = { - { 12, -51, 4 }, + double[][] testData3x3NonSingular = { + { 12, -51, 4 }, { 6, 167, -68 }, { -4, 24, -41 } }; - double[][] testData3x3Singular = { - { 1, 2, 2 }, + double[][] testData3x3Singular = { + { 1, 2, 2 }, { 2, 4, 6 }, { 4, 8, 12 } }; - double[][] testData3x4 = { - { 12, -51, 4, 1 }, + double[][] testData3x4 = { + { 12, -51, 4, 1 }, { 6, 167, -68, 2 }, { -4, 24, -41, 3 } }; - double[][] testData4x3 = { - { 12, -51, 4 }, + double[][] testData4x3 = { + { 12, -51, 4 }, { 6, 167, -68 }, - { -4, 24, -41 }, + { -4, 24, -41 }, { -5, 34, 7 } }; diff --git a/src/test/java/org/apache/commons/math/linear/RealMatrixImplTest.java b/src/test/java/org/apache/commons/math/linear/RealMatrixImplTest.java index 6391fe6be..6f1b685a8 100644 --- a/src/test/java/org/apache/commons/math/linear/RealMatrixImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/RealMatrixImplTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,45 +29,45 @@ import org.apache.commons.math.TestUtils; */ @Deprecated public final class RealMatrixImplTest extends TestCase { - + // 3 x 3 identity matrix protected double[][] id = { {1d,0d,0d}, {0d,1d,0d}, {0d,0d,1d} }; - + // Test data for group operations protected double[][] testData = { {1d,2d,3d}, {2d,5d,3d}, {1d,0d,8d} }; protected double[][] testDataLU = {{2d, 5d, 3d}, {.5d, -2.5d, 6.5d}, {0.5d, 0.2d, .2d}}; protected double[][] testDataPlus2 = { {3d,4d,5d}, {4d,7d,5d}, {3d,2d,10d} }; - protected double[][] testDataMinus = { {-1d,-2d,-3d}, {-2d,-5d,-3d}, + protected double[][] testDataMinus = { {-1d,-2d,-3d}, {-2d,-5d,-3d}, {-1d,0d,-8d} }; protected double[] testDataRow1 = {1d,2d,3d}; protected double[] testDataCol3 = {3d,3d,8d}; - protected double[][] testDataInv = + protected double[][] testDataInv = { {-40d,16d,9d}, {13d,-5d,-3d}, {5d,-2d,-1d} }; protected double[] preMultTest = {8,12,33}; protected double[][] testData2 ={ {1d,2d,3d}, {2d,5d,3d}}; protected double[][] testData2T = { {1d,2d}, {2d,5d}, {3d,3d}}; - protected double[][] testDataPlusInv = + protected double[][] testDataPlusInv = { {-39d,18d,12d}, {15d,0d,0d}, {6d,-2d,7d} }; - + // lu decomposition tests protected double[][] luData = { {2d,3d,3d}, {0d,5d,7d}, {6d,9d,8d} }; protected double[][] luDataLUDecomposition = { {6d,9d,8d}, {0d,5d,7d}, {0.33333333333333,0d,0.33333333333333} }; - + // singular matrices protected double[][] singular = { {2d,3d}, {2d,3d} }; protected double[][] bigSingular = {{1d,2d,3d,4d}, {2d,5d,3d,4d}, {7d,3d,256d,1930d}, {3d,7d,6d,8d}}; // 4th row = 1st + 2nd protected double[][] detData = { {1d,2d,3d}, {4d,5d,6d}, {7d,8d,10d} }; protected double[][] detData2 = { {1d, 3d}, {2d, 4d}}; - + // vectors protected double[] testVector = {1,2,3}; protected double[] testVector2 = {1,2,3,4}; - + // submatrix accessor tests protected double[][] subTestData = {{1, 2, 3, 4}, {1.5, 2.5, 3.5, 4.5}, - {2, 4, 6, 8}, {4, 5, 6, 7}}; + {2, 4, 6, 8}, {4, 5, 6, 7}}; // array selections protected double[][] subRows02Cols13 = { {2, 4}, {4, 8}}; protected double[][] subRows03Cols12 = { {2, 3}, {5, 6}}; @@ -85,21 +85,21 @@ public final class RealMatrixImplTest extends TestCase { // column matrices protected double[][] subColumn1 = {{2}, {2.5}, {4}, {5}}; protected double[][] subColumn3 = {{4}, {4.5}, {8}, {7}}; - + // tolerances protected double entryTolerance = 10E-16; protected double normTolerance = 10E-14; - + public RealMatrixImplTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(RealMatrixImplTest.class); suite.setName("RealMatrixImpl Tests"); return suite; } - + /** test dimensions */ public void testDimensions() { RealMatrixImpl m = new RealMatrixImpl(testData); @@ -110,8 +110,8 @@ public final class RealMatrixImplTest extends TestCase { assertEquals("testData2 row dimension",m2.getRowDimension(),2); assertEquals("testData2 column dimension",m2.getColumnDimension(),3); assertTrue("testData2 is not square",!m2.isSquare()); - } - + } + /** test copy functions */ public void testCopyFunctions() { RealMatrixImpl m1 = new RealMatrixImpl(testData); @@ -120,8 +120,8 @@ public final class RealMatrixImplTest extends TestCase { RealMatrixImpl m3 = new RealMatrixImpl(testData); RealMatrixImpl m4 = new RealMatrixImpl(m3.getData(), false); assertEquals(m4,m3); - } - + } + /** test add */ public void testAdd() { RealMatrixImpl m = new RealMatrixImpl(testData); @@ -134,9 +134,9 @@ public final class RealMatrixImplTest extends TestCase { testDataPlusInv[row][col],sumEntries[row][col], entryTolerance); } - } + } } - + /** test add failure */ public void testAddFail() { RealMatrixImpl m = new RealMatrixImpl(testData); @@ -148,7 +148,7 @@ public final class RealMatrixImplTest extends TestCase { // ignored } } - + /** test norm */ public void testNorm() { RealMatrixImpl m = new RealMatrixImpl(testData); @@ -156,7 +156,7 @@ public final class RealMatrixImplTest extends TestCase { assertEquals("testData norm",14d,m.getNorm(),entryTolerance); assertEquals("testData2 norm",7d,m2.getNorm(),entryTolerance); } - + /** test Frobenius norm */ public void testFrobeniusNorm() { RealMatrixImpl m = new RealMatrixImpl(testData); @@ -164,21 +164,21 @@ public final class RealMatrixImplTest extends TestCase { assertEquals("testData Frobenius norm", Math.sqrt(117.0), m.getFrobeniusNorm(), entryTolerance); assertEquals("testData2 Frobenius norm", Math.sqrt(52.0), m2.getFrobeniusNorm(), entryTolerance); } - + /** test m-n = m + -n */ public void testPlusMinus() { RealMatrixImpl m = new RealMatrixImpl(testData); RealMatrixImpl m2 = new RealMatrixImpl(testDataInv); TestUtils.assertEquals("m-n = m + -n",m.subtract(m2), - m2.scalarMultiply(-1d).add(m),entryTolerance); + m2.scalarMultiply(-1d).add(m),entryTolerance); try { m.subtract(new RealMatrixImpl(testData2)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + /** test multiply */ public void testMultiply() { RealMatrixImpl m = new RealMatrixImpl(testData); @@ -194,28 +194,28 @@ public final class RealMatrixImplTest extends TestCase { TestUtils.assertEquals("identity multiply",identity.multiply(mInv), mInv,entryTolerance); TestUtils.assertEquals("identity multiply",m2.multiply(identity), - m2,entryTolerance); + m2,entryTolerance); try { m.multiply(new RealMatrixImpl(bigSingular)); fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } - } - + } + } + //Additional Test for RealMatrixImplTest.testMultiply private double[][] d3 = new double[][] {{1,2,3,4},{5,6,7,8}}; private double[][] d4 = new double[][] {{1},{2},{3},{4}}; private double[][] d5 = new double[][] {{30},{70}}; - - public void testMultiply2() { - RealMatrix m3 = new RealMatrixImpl(d3); + + public void testMultiply2() { + RealMatrix m3 = new RealMatrixImpl(d3); RealMatrix m4 = new RealMatrixImpl(d4); RealMatrix m5 = new RealMatrixImpl(d5); TestUtils.assertEquals("m3*m4=m5", m3.multiply(m4), m5, entryTolerance); - } - + } + /** test trace */ public void testTrace() { RealMatrix m = new RealMatrixImpl(id); @@ -226,16 +226,16 @@ public final class RealMatrixImplTest extends TestCase { fail("Expecting NonSquareMatrixException"); } catch (NonSquareMatrixException ex) { // ignored - } + } } - + /** test sclarAdd */ public void testScalarAdd() { RealMatrix m = new RealMatrixImpl(testData); TestUtils.assertEquals("scalar add",new RealMatrixImpl(testDataPlus2), m.scalarAdd(2d),entryTolerance); } - + /** test operate */ public void testOperate() { RealMatrix m = new RealMatrixImpl(id); @@ -249,7 +249,7 @@ public final class RealMatrixImplTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } /** test issue MATH-209 */ @@ -263,10 +263,10 @@ public final class RealMatrixImplTest extends TestCase { assertEquals( 7.0, b[1], 1.0e-12); assertEquals(11.0, b[2], 1.0e-12); } - + /** test transpose */ public void testTranspose() { - RealMatrix m = new RealMatrixImpl(testData); + RealMatrix m = new RealMatrixImpl(testData); RealMatrix mIT = new LUDecompositionImpl(m).getSolver().getInverse().transpose(); RealMatrix mTI = new LUDecompositionImpl(m.transpose()).getSolver().getInverse(); TestUtils.assertEquals("inverse-transpose", mIT, mTI, normTolerance); @@ -274,7 +274,7 @@ public final class RealMatrixImplTest extends TestCase { RealMatrix mt = new RealMatrixImpl(testData2T); TestUtils.assertEquals("transpose",mt,m.transpose(),normTolerance); } - + /** test preMultiply by vector */ public void testPremultiplyVector() { RealMatrix m = new RealMatrixImpl(testData); @@ -290,13 +290,13 @@ public final class RealMatrixImplTest extends TestCase { // ignored } } - + public void testPremultiply() { - RealMatrix m3 = new RealMatrixImpl(d3); + RealMatrix m3 = new RealMatrixImpl(d3); RealMatrix m4 = new RealMatrixImpl(d4); RealMatrix m5 = new RealMatrixImpl(d5); TestUtils.assertEquals("m3*m4=m5", m4.preMultiply(m3), m5, entryTolerance); - + RealMatrixImpl m = new RealMatrixImpl(testData); RealMatrixImpl mInv = new RealMatrixImpl(testDataInv); RealMatrixImpl identity = new RealMatrixImpl(id); @@ -313,9 +313,9 @@ public final class RealMatrixImplTest extends TestCase { fail("Expecting illegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored - } + } } - + public void testGetVectors() { RealMatrix m = new RealMatrixImpl(testData); TestUtils.assertEquals("get row",m.getRow(0),testDataRow1,entryTolerance); @@ -333,7 +333,7 @@ public final class RealMatrixImplTest extends TestCase { // ignored } } - + public void testGetEntry() { RealMatrix m = new RealMatrixImpl(testData); assertEquals("get entry",m.getEntry(0,1),2d,entryTolerance); @@ -344,7 +344,7 @@ public final class RealMatrixImplTest extends TestCase { // expected } } - + /** test examples in user guide */ public void testExamples() { // Create a real matrix with two rows and three columns @@ -358,10 +358,10 @@ public final class RealMatrixImplTest extends TestCase { assertEquals(2, p.getRowDimension()); assertEquals(2, p.getColumnDimension()); // Invert p - RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse(); + RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse(); assertEquals(2, pInverse.getRowDimension()); assertEquals(2, pInverse.getColumnDimension()); - + // Solve example double[][] coefficientsData = {{2, 3, -2}, {-1, 7, 6}, {4, -3, -5}}; RealMatrix coefficients = new RealMatrixImpl(coefficientsData); @@ -369,22 +369,22 @@ public final class RealMatrixImplTest extends TestCase { double[] solution = new LUDecompositionImpl(coefficients).getSolver().solve(constants); assertEquals(2 * solution[0] + 3 * solution[1] -2 * solution[2], constants[0], 1E-12); assertEquals(-1 * solution[0] + 7 * solution[1] + 6 * solution[2], constants[1], 1E-12); - assertEquals(4 * solution[0] - 3 * solution[1] -5 * solution[2], constants[2], 1E-12); - + assertEquals(4 * solution[0] - 3 * solution[1] -5 * solution[2], constants[2], 1E-12); + } - + // test submatrix accessors public void testGetSubMatrix() { RealMatrix m = new RealMatrixImpl(subTestData); checkGetSubMatrix(m, subRows23Cols00, 2 , 3 , 0, 0, false); checkGetSubMatrix(m, subRows00Cols33, 0 , 0 , 3, 3, false); - checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3, false); - checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }, false); - checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }, false); - checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }, false); - checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }, false); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); - checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); + checkGetSubMatrix(m, subRows01Cols23, 0 , 1 , 2, 3, false); + checkGetSubMatrix(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }, false); + checkGetSubMatrix(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }, false); + checkGetSubMatrix(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }, false); + checkGetSubMatrix(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }, false); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); + checkGetSubMatrix(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); checkGetSubMatrix(m, null, 1, 0, 2, 4, true); checkGetSubMatrix(m, null, -1, 1, 2, 2, true); checkGetSubMatrix(m, null, 1, 0, 2, 2, true); @@ -408,7 +408,7 @@ public final class RealMatrixImplTest extends TestCase { } } } - + private void checkGetSubMatrix(RealMatrix m, double[][] reference, int[] selectedRows, int[] selectedColumns, boolean mustFail) { @@ -429,14 +429,14 @@ public final class RealMatrixImplTest extends TestCase { RealMatrix m = new RealMatrixImpl(subTestData); checkCopy(m, subRows23Cols00, 2 , 3 , 0, 0, false); checkCopy(m, subRows00Cols33, 0 , 0 , 3, 3, false); - checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3, false); - checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }, false); - checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }, false); - checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }, false); - checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }, false); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); - checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); - + checkCopy(m, subRows01Cols23, 0 , 1 , 2, 3, false); + checkCopy(m, subRows02Cols13, new int[] { 0, 2 }, new int[] { 1, 3 }, false); + checkCopy(m, subRows03Cols12, new int[] { 0, 3 }, new int[] { 1, 2 }, false); + checkCopy(m, subRows03Cols123, new int[] { 0, 3 }, new int[] { 1, 2, 3 }, false); + checkCopy(m, subRows20Cols123, new int[] { 2, 0 }, new int[] { 1, 2, 3 }, false); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); + checkCopy(m, subRows31Cols31, new int[] { 3, 1 }, new int[] { 3, 1 }, false); + checkCopy(m, null, 1, 0, 2, 4, true); checkCopy(m, null, -1, 1, 2, 2, true); checkCopy(m, null, 1, 0, 2, 2, true); @@ -463,7 +463,7 @@ public final class RealMatrixImplTest extends TestCase { } } } - + private void checkCopy(RealMatrix m, double[][] reference, int[] selectedRows, int[] selectedColumns, boolean mustFail) { @@ -487,9 +487,9 @@ public final class RealMatrixImplTest extends TestCase { RealMatrix m = new RealMatrixImpl(subTestData); RealMatrix mRow0 = new RealMatrixImpl(subRow0); RealMatrix mRow3 = new RealMatrixImpl(subRow3); - assertEquals("Row0", mRow0, + assertEquals("Row0", mRow0, m.getRowMatrix(0)); - assertEquals("Row3", mRow3, + assertEquals("Row3", mRow3, m.getRowMatrix(3)); try { m.getRowMatrix(-1); @@ -504,7 +504,7 @@ public final class RealMatrixImplTest extends TestCase { // expected } } - + public void testSetRowMatrix() { RealMatrix m = new RealMatrixImpl(subTestData); RealMatrix mRow3 = new RealMatrixImpl(subRow3); @@ -524,14 +524,14 @@ public final class RealMatrixImplTest extends TestCase { // expected } } - + public void testGetColumnMatrix() { RealMatrix m = new RealMatrixImpl(subTestData); RealMatrix mColumn1 = new RealMatrixImpl(subColumn1); RealMatrix mColumn3 = new RealMatrixImpl(subColumn3); - assertEquals("Column1", mColumn1, + assertEquals("Column1", mColumn1, m.getColumnMatrix(1)); - assertEquals("Column3", mColumn3, + assertEquals("Column3", mColumn3, m.getColumnMatrix(3)); try { m.getColumnMatrix(-1); @@ -606,7 +606,7 @@ public final class RealMatrixImplTest extends TestCase { // expected } } - + public void testGetColumnVector() { RealMatrix m = new RealMatrixImpl(subTestData); RealVector mColumn1 = columnToVector(subColumn1); @@ -691,7 +691,7 @@ public final class RealMatrixImplTest extends TestCase { // expected } } - + public void testGetColumn() { RealMatrix m = new RealMatrixImpl(subTestData); double[] mColumn1 = columnToArray(subColumn1); @@ -743,10 +743,10 @@ public final class RealMatrixImplTest extends TestCase { private void checkArrays(double[] expected, double[] actual) { assertEquals(expected.length, actual.length); for (int i = 0; i < expected.length; ++i) { - assertEquals(expected[i], actual[i]); + assertEquals(expected[i], actual[i]); } } - + public void testEqualsAndHashCode() { RealMatrixImpl m = new RealMatrixImpl(testData); RealMatrixImpl m1 = (RealMatrixImpl) m.copy(); @@ -757,9 +757,9 @@ public final class RealMatrixImplTest extends TestCase { assertEquals(m, m1); assertFalse(m.equals(null)); assertFalse(m.equals(mt)); - assertFalse(m.equals(new RealMatrixImpl(bigSingular))); + assertFalse(m.equals(new RealMatrixImpl(bigSingular))); } - + public void testToString() { RealMatrixImpl m = new RealMatrixImpl(testData); assertEquals("RealMatrixImpl{{1.0,2.0,3.0},{2.0,5.0,3.0},{1.0,0.0,8.0}}", @@ -768,45 +768,45 @@ public final class RealMatrixImplTest extends TestCase { assertEquals("RealMatrixImpl{}", m.toString()); } - + public void testSetSubMatrix() throws Exception { RealMatrixImpl m = new RealMatrixImpl(testData); m.setSubMatrix(detData2,1,1); RealMatrix expected = MatrixUtils.createRealMatrix (new double[][] {{1.0,2.0,3.0},{2.0,1.0,3.0},{1.0,2.0,4.0}}); - assertEquals(expected, m); - + assertEquals(expected, m); + m.setSubMatrix(detData2,0,0); expected = MatrixUtils.createRealMatrix (new double[][] {{1.0,3.0,3.0},{2.0,4.0,3.0},{1.0,2.0,4.0}}); - assertEquals(expected, m); - - m.setSubMatrix(testDataPlus2,0,0); + assertEquals(expected, m); + + m.setSubMatrix(testDataPlus2,0,0); expected = MatrixUtils.createRealMatrix (new double[][] {{3.0,4.0,5.0},{4.0,7.0,5.0},{3.0,2.0,10.0}}); - assertEquals(expected, m); - + assertEquals(expected, m); + // dimension overflow - try { + try { m.setSubMatrix(testData,1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } // dimension underflow - try { + try { m.setSubMatrix(testData,-1,1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - try { + try { m.setSubMatrix(testData,1,-1); fail("expecting MatrixIndexException"); } catch (MatrixIndexException e) { // expected } - + // null try { m.setSubMatrix(null,1,1); @@ -827,7 +827,7 @@ public final class RealMatrixImplTest extends TestCase { } catch (IllegalStateException e) { // expected } - + // ragged try { m.setSubMatrix(new double[][] {{1}, {2, 3}}, 0, 0); @@ -835,7 +835,7 @@ public final class RealMatrixImplTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + // empty try { m.setSubMatrix(new double[][] {{}}, 0, 0); @@ -843,7 +843,7 @@ public final class RealMatrixImplTest extends TestCase { } catch (IllegalArgumentException e) { // expected } - + } public void testWalk() { @@ -862,11 +862,11 @@ public final class RealMatrixImplTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -882,11 +882,11 @@ public final class RealMatrixImplTest extends TestCase { m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -902,11 +902,11 @@ public final class RealMatrixImplTest extends TestCase { m.walkInRowOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -922,11 +922,11 @@ public final class RealMatrixImplTest extends TestCase { m.walkInColumnOrder(getVisitor, 1, rows - 2, 1, columns - 2); assertEquals((rows - 2) * (columns - 2), getVisitor.getCount()); for (int i = 0; i < rows; ++i) { - assertEquals(0.0, m.getEntry(i, 0), 0); + assertEquals(0.0, m.getEntry(i, 0), 0); assertEquals(0.0, m.getEntry(i, columns - 1), 0); } for (int j = 0; j < columns; ++j) { - assertEquals(0.0, m.getEntry(0, j), 0); + assertEquals(0.0, m.getEntry(0, j), 0); assertEquals(0.0, m.getEntry(rows - 1, j), 0); } @@ -936,8 +936,8 @@ public final class RealMatrixImplTest extends TestCase { RealMatrixImpl m = new RealMatrixImpl(testData); assertEquals(m,TestUtils.serializeAndRecover(m)); } - - + + private static class SetVisitor extends DefaultRealMatrixChangingVisitor { @Override public double visit(int i, int j, double value) { @@ -958,14 +958,14 @@ public final class RealMatrixImplTest extends TestCase { } //--------------- -----------------Protected methods - + /** extracts the l and u matrices from compact lu representation */ - protected void splitLU(RealMatrix lu, double[][] lowerData, double[][] upperData) throws InvalidMatrixException { + protected void splitLU(RealMatrix lu, double[][] lowerData, double[][] upperData) throws InvalidMatrixException { if (!lu.isSquare() || lowerData.length != lowerData[0].length || upperData.length != upperData[0].length || lowerData.length != upperData.length || lowerData.length != lu.getRowDimension()) { throw new InvalidMatrixException("incorrect dimensions"); - } + } int n = lu.getRowDimension(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { @@ -978,11 +978,11 @@ public final class RealMatrixImplTest extends TestCase { } else { lowerData[i][j] = 0d; upperData[i][j] = lu.getEntry(i, j); - } + } } } } - + /** Returns the result of applying the given row permutation to the matrix */ protected RealMatrix permuteRows(RealMatrix matrix, int[] permutation) { if (!matrix.isSquare() || matrix.getRowDimension() != permutation.length) { @@ -998,7 +998,7 @@ public final class RealMatrixImplTest extends TestCase { } return new RealMatrixImpl(out); } - + // /** Useful for debugging */ // private void dumpMatrix(RealMatrix m) { // for (int i = 0; i < m.getRowDimension(); i++) { @@ -1009,6 +1009,6 @@ public final class RealMatrixImplTest extends TestCase { // System.out.println(os); // } // } - + } diff --git a/src/test/java/org/apache/commons/math/linear/RealVectorFormatAbstractTest.java b/src/test/java/org/apache/commons/math/linear/RealVectorFormatAbstractTest.java index 487a419a0..f1481325e 100644 --- a/src/test/java/org/apache/commons/math/linear/RealVectorFormatAbstractTest.java +++ b/src/test/java/org/apache/commons/math/linear/RealVectorFormatAbstractTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,7 +27,7 @@ import junit.framework.TestCase; import org.apache.commons.math.util.CompositeFormat; public abstract class RealVectorFormatAbstractTest extends TestCase { - + RealVectorFormat realVectorFormat = null; RealVectorFormat realVectorFormatSquare = null; @@ -42,11 +42,11 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { nf.setMaximumFractionDigits(2); realVectorFormatSquare = new RealVectorFormat("[", "]", " : ", nf); } - + public void testSimpleNoDecimals() { ArrayRealVector c = new ArrayRealVector(new double[] {1, 1, 1}); String expected = "{1; 1; 1}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } @@ -57,7 +57,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "23; 1" + getDecimalCharacter() + "43; 1" + getDecimalCharacter() + "63}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } @@ -68,7 +68,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "23; 1" + getDecimalCharacter() + "43; 1" + getDecimalCharacter() + "63}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } @@ -79,7 +79,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "23; 1" + getDecimalCharacter() + "43; 1" + getDecimalCharacter() + "63}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } @@ -90,7 +90,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "23; -1" + getDecimalCharacter() + "43; 1" + getDecimalCharacter() + "63}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } @@ -101,37 +101,37 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "23; 1" + getDecimalCharacter() + "43; -1" + getDecimalCharacter() + "63}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } public void testNonDefaultSetting() { ArrayRealVector c = new ArrayRealVector(new double[] {1, 1, 1}); String expected = "[1 : 1 : 1]"; - String actual = realVectorFormatSquare.format(c); + String actual = realVectorFormatSquare.format(c); assertEquals(expected, actual); } - + public void testStaticFormatRealVectorImpl() { Locale defaultLocal = Locale.getDefault(); Locale.setDefault(getLocale()); - + ArrayRealVector c = new ArrayRealVector(new double[] {232.222, -342.33, 432.444}); String expected = "{232" + getDecimalCharacter() + "22; -342" + getDecimalCharacter() + "33; 432" + getDecimalCharacter() + "44}"; - String actual = RealVectorFormat.formatRealVector(c); + String actual = RealVectorFormat.formatRealVector(c); assertEquals(expected, actual); - + Locale.setDefault(defaultLocal); } public void testNan() { ArrayRealVector c = new ArrayRealVector(new double[] {Double.NaN, Double.NaN, Double.NaN}); String expected = "{(NaN); (NaN); (NaN)}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } @@ -140,7 +140,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY }); String expected = "{(Infinity); (Infinity); (Infinity)}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } @@ -149,7 +149,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY }); String expected = "{(-Infinity); (-Infinity); (-Infinity)}"; - String actual = realVectorFormat.format(c); + String actual = realVectorFormat.format(c); assertEquals(expected, actual); } @@ -157,7 +157,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { String source = "{1; 1; 1}"; ArrayRealVector expected = new ArrayRealVector(new double[] {1, 1, 1}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -184,7 +184,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "63}"; ArrayRealVector expected = new ArrayRealVector(new double[] {1.23, 1.43, 1.63}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -199,7 +199,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "6333}"; ArrayRealVector expected = new ArrayRealVector(new double[] {1.2323, 1.4343, 1.6333}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -214,7 +214,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "6333}"; ArrayRealVector expected = new ArrayRealVector(new double[] {-1.2323, 1.4343, 1.6333}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -229,7 +229,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "6333}"; ArrayRealVector expected = new ArrayRealVector(new double[] {1.2323, -1.4343, 1.6333}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -244,7 +244,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "6333}"; ArrayRealVector expected = new ArrayRealVector(new double[] {1.2323, 1.4343, -1.6333}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -259,7 +259,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "6333}"; ArrayRealVector expected = new ArrayRealVector(new double[] {-1.2323, -1.4343, -1.6333}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -274,7 +274,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "6333}"; ArrayRealVector expected = new ArrayRealVector(new double[] {0.0, -1.4343, 1.6333}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -289,17 +289,17 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { "6333]"; ArrayRealVector expected = new ArrayRealVector(new double[] {1.2323, 1.4343, 1.6333}); try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormatSquare.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormatSquare.parseObject(source); assertEquals(expected, actual); } catch (ParseException ex) { fail(ex.getMessage()); } } - + public void testParseNan() { String source = "{(NaN); (NaN); (NaN)}"; try { - ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector) realVectorFormat.parseObject(source); assertEquals(new ArrayRealVector(new double[] {Double.NaN, Double.NaN, Double.NaN}), actual); } catch (ParseException ex) { fail(ex.getMessage()); @@ -309,7 +309,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { public void testParsePositiveInfinity() { String source = "{(Infinity); (Infinity); (Infinity)}"; try { - ArrayRealVector actual = (ArrayRealVector)realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector)realVectorFormat.parseObject(source); assertEquals(new ArrayRealVector(new double[] { Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY }), actual); @@ -321,7 +321,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { public void testParseNegativeInfinity() { String source = "{(-Infinity); (-Infinity); (-Infinity)}"; try { - ArrayRealVector actual = (ArrayRealVector)realVectorFormat.parseObject(source); + ArrayRealVector actual = (ArrayRealVector)realVectorFormat.parseObject(source); assertEquals(new ArrayRealVector(new double[] { Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY }), actual); @@ -352,7 +352,7 @@ public abstract class RealVectorFormatAbstractTest extends TestCase { assertNotNull(cf); assertEquals(nf, cf.getFormat()); } - + public void testFormatObject() { try { CompositeFormat cf = new RealVectorFormat(); diff --git a/src/test/java/org/apache/commons/math/linear/RealVectorFormatTest.java b/src/test/java/org/apache/commons/math/linear/RealVectorFormatTest.java index 4f428a643..e7368b53c 100644 --- a/src/test/java/org/apache/commons/math/linear/RealVectorFormatTest.java +++ b/src/test/java/org/apache/commons/math/linear/RealVectorFormatTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/test/java/org/apache/commons/math/linear/SingularValueDecompositionImplTest.java b/src/test/java/org/apache/commons/math/linear/SingularValueDecompositionImplTest.java index 6ae143c05..0f33071f8 100644 --- a/src/test/java/org/apache/commons/math/linear/SingularValueDecompositionImplTest.java +++ b/src/test/java/org/apache/commons/math/linear/SingularValueDecompositionImplTest.java @@ -199,7 +199,7 @@ public class SingularValueDecompositionImplTest extends TestCase { assertTrue(u == svd.getU()); assertTrue(s == svd.getS()); assertTrue(v == svd.getV()); - + } /** test matrices values */ diff --git a/src/test/java/org/apache/commons/math/linear/SparseFieldMatrixTest.java b/src/test/java/org/apache/commons/math/linear/SparseFieldMatrixTest.java index d2539baa9..a7aa5bdfb 100644 --- a/src/test/java/org/apache/commons/math/linear/SparseFieldMatrixTest.java +++ b/src/test/java/org/apache/commons/math/linear/SparseFieldMatrixTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -123,8 +123,8 @@ public class SparseFieldMatrixTest extends TestCase { } catch (FractionConversionException e) { // ignore, can't happen } - - + + } public static Test suite() { @@ -165,8 +165,8 @@ public class SparseFieldMatrixTest extends TestCase { FieldMatrix mPlusMInv = m.add(mInv); for (int row = 0; row < m.getRowDimension(); row++) { for (int col = 0; col < m.getColumnDimension(); col++) { - assertEquals("sum entry entry", - mDataPlusInv.getEntry(row, col).doubleValue(), mPlusMInv.getEntry(row, col).doubleValue(), + assertEquals("sum entry entry", + mDataPlusInv.getEntry(row, col).doubleValue(), mPlusMInv.getEntry(row, col).doubleValue(), entryTolerance); } } @@ -184,7 +184,7 @@ public class SparseFieldMatrixTest extends TestCase { } } - + /** test m-n = m + -n */ public void testPlusMinus() { SparseFieldMatrix m = createSparseMatrix(testData); @@ -254,7 +254,7 @@ public class SparseFieldMatrixTest extends TestCase { /** test sclarAdd */ public void testScalarAdd() { FieldMatrix m = createSparseMatrix(testData); - assertClose("scalar add", createSparseMatrix(testDataPlus2), + assertClose("scalar add", createSparseMatrix(testDataPlus2), m.scalarAdd(new Fraction(2)), entryTolerance); } @@ -287,8 +287,8 @@ public class SparseFieldMatrixTest extends TestCase { /** test transpose */ public void testTranspose() { - - FieldMatrix m = createSparseMatrix(testData); + + FieldMatrix m = createSparseMatrix(testData); FieldMatrix mIT = new FieldLUDecompositionImpl(m).getSolver().getInverse().transpose(); FieldMatrix mTI = new FieldLUDecompositionImpl(m.transpose()).getSolver().getInverse(); assertClose("inverse-transpose", mIT, mTI, normTolerance); @@ -380,7 +380,7 @@ public class SparseFieldMatrixTest extends TestCase { assertEquals(2, p.getRowDimension()); assertEquals(2, p.getColumnDimension()); // Invert p - FieldMatrix pInverse = new FieldLUDecompositionImpl(p).getSolver().getInverse(); + FieldMatrix pInverse = new FieldLUDecompositionImpl(p).getSolver().getInverse(); assertEquals(2, pInverse.getRowDimension()); assertEquals(2, pInverse.getColumnDimension()); @@ -413,17 +413,17 @@ public class SparseFieldMatrixTest extends TestCase { assertEquals("Rows23Cols00", mRows23Cols00, m.getSubMatrix(2, 3, 0, 0)); assertEquals("Rows00Cols33", mRows00Cols33, m.getSubMatrix(0, 0, 3, 3)); assertEquals("Rows01Cols23", mRows01Cols23, m.getSubMatrix(0, 1, 2, 3)); - assertEquals("Rows02Cols13", mRows02Cols13, + assertEquals("Rows02Cols13", mRows02Cols13, m.getSubMatrix(new int[] { 0, 2 }, new int[] { 1, 3 })); - assertEquals("Rows03Cols12", mRows03Cols12, + assertEquals("Rows03Cols12", mRows03Cols12, m.getSubMatrix(new int[] { 0, 3 }, new int[] { 1, 2 })); - assertEquals("Rows03Cols123", mRows03Cols123, + assertEquals("Rows03Cols123", mRows03Cols123, m.getSubMatrix(new int[] { 0, 3 }, new int[] { 1, 2, 3 })); - assertEquals("Rows20Cols123", mRows20Cols123, + assertEquals("Rows20Cols123", mRows20Cols123, m.getSubMatrix(new int[] { 2, 0 }, new int[] { 1, 2, 3 })); - assertEquals("Rows31Cols31", mRows31Cols31, + assertEquals("Rows31Cols31", mRows31Cols31, m.getSubMatrix(new int[] { 3, 1 }, new int[] { 3, 1 })); - assertEquals("Rows31Cols31", mRows31Cols31, + assertEquals("Rows31Cols31", mRows31Cols31, m.getSubMatrix(new int[] { 3, 1 }, new int[] { 3, 1 })); try { @@ -568,7 +568,7 @@ public class SparseFieldMatrixTest extends TestCase { /* Disable for now public void testToString() { SparseFieldMatrix m = createSparseMatrix(testData); - assertEquals("SparseFieldMatrix{{1.0,2.0,3.0},{2.0,5.0,3.0},{1.0,0.0,8.0}}", + assertEquals("SparseFieldMatrix{{1.0,2.0,3.0},{2.0,5.0,3.0},{1.0,0.0,8.0}}", m.toString()); m = new SparseFieldMatrix(field, 1, 1); assertEquals("SparseFieldMatrix{{0.0}}", m.toString()); @@ -593,8 +593,8 @@ public class SparseFieldMatrixTest extends TestCase { assertEquals(expected, m); // javadoc example - SparseFieldMatrix matrix = - createSparseMatrix(new Fraction[][] { + SparseFieldMatrix matrix = + createSparseMatrix(new Fraction[][] { { new Fraction(1), new Fraction(2), new Fraction(3), new Fraction(4) }, { new Fraction(5), new Fraction(6), new Fraction(7), new Fraction(8) }, { new Fraction(9), new Fraction(0), new Fraction(1), new Fraction(2) } }); matrix.setSubMatrix(new Fraction[][] { { new Fraction(3), new Fraction(4) }, { new Fraction(5), new Fraction(6) } }, 1, 1); expected = createSparseMatrix(new Fraction[][] { @@ -663,7 +663,7 @@ public class SparseFieldMatrixTest extends TestCase { for(int j=0; j < m.getColumnDimension(); j++){ assertEquals(msg, m.getEntry(i,j).doubleValue(), n.getEntry(i,j).doubleValue(), tolerance); } - + } } @@ -678,7 +678,7 @@ public class SparseFieldMatrixTest extends TestCase { tolerance); } } - + private SparseFieldMatrix createSparseMatrix(Fraction[][] data) { SparseFieldMatrix matrix = new SparseFieldMatrix(field, data.length, data[0].length); for (int row = 0; row < data.length; row++) { diff --git a/src/test/java/org/apache/commons/math/linear/SparseFieldVectorTest.java b/src/test/java/org/apache/commons/math/linear/SparseFieldVectorTest.java index 90adb840e..4e6b28277 100644 --- a/src/test/java/org/apache/commons/math/linear/SparseFieldVectorTest.java +++ b/src/test/java/org/apache/commons/math/linear/SparseFieldVectorTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,7 +31,7 @@ import junit.framework.TestCase; */ public class SparseFieldVectorTest extends TestCase { - // + // protected Fraction[][] ma1 = {{new Fraction(1), new Fraction(2), new Fraction(3)}, {new Fraction(4), new Fraction(5), new Fraction(6)}, {new Fraction(7), new Fraction(8), new Fraction(9)}}; protected Fraction[] vec1 = {new Fraction(1), new Fraction(2), new Fraction(3)}; protected Fraction[] vec2 = {new Fraction(4), new Fraction(5), new Fraction(6)}; @@ -47,7 +47,7 @@ public class SparseFieldVectorTest extends TestCase { protected FractionField field = FractionField.getInstance(); - public void testMapFunctions() throws FractionConversionException { + public void testMapFunctions() throws FractionConversionException { SparseFieldVector v1 = new SparseFieldVector(field,vec1); //octave = v1 .+ 2.0 @@ -108,11 +108,11 @@ public class SparseFieldVectorTest extends TestCase { } - public void testBasicFunctions() throws FractionConversionException { + public void testBasicFunctions() throws FractionConversionException { SparseFieldVector v1 = new SparseFieldVector(field,vec1); SparseFieldVector v2 = new SparseFieldVector(field,vec2); - SparseFieldVector v2_t = new SparseFieldVector(field,vec2); + SparseFieldVector v2_t = new SparseFieldVector(field,vec2); //octave = v1 + v2 FieldVector v_add = v1.add(v2); @@ -168,19 +168,19 @@ public class SparseFieldVectorTest extends TestCase { } - public void testMisc() { + public void testMisc() { SparseFieldVector v1 = new SparseFieldVector(field,vec1); String out1 = v1.toString(); assertTrue("some output ", out1.length()!=0); try { - v1.checkVectorDimensions(2); + v1.checkVectorDimensions(2); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); - } + } } diff --git a/src/test/java/org/apache/commons/math/linear/SparseRealMatrixTest.java b/src/test/java/org/apache/commons/math/linear/SparseRealMatrixTest.java index 727deee8f..6b0af3e8f 100644 --- a/src/test/java/org/apache/commons/math/linear/SparseRealMatrixTest.java +++ b/src/test/java/org/apache/commons/math/linear/SparseRealMatrixTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,7 @@ import org.apache.commons.math.TestUtils; /** * Test cases for the {@link OpenMapRealMatrix} class. - * + * * @version $Revision$ $Date: 2008-11-07 06:48:13 -0800 (Fri, 07 Nov * 2008) $ */ @@ -146,8 +146,8 @@ public final class SparseRealMatrixTest extends TestCase { RealMatrix mPlusMInv = m.add(mInv); for (int row = 0; row < m.getRowDimension(); row++) { for (int col = 0; col < m.getColumnDimension(); col++) { - assertEquals("sum entry entry", - mDataPlusInv.getEntry(row, col), mPlusMInv.getEntry(row, col), + assertEquals("sum entry entry", + mDataPlusInv.getEntry(row, col), mPlusMInv.getEntry(row, col), entryTolerance); } } @@ -242,7 +242,7 @@ public final class SparseRealMatrixTest extends TestCase { /** test sclarAdd */ public void testScalarAdd() { RealMatrix m = createSparseMatrix(testData); - assertClose("scalar add", createSparseMatrix(testDataPlus2), + assertClose("scalar add", createSparseMatrix(testDataPlus2), m.scalarAdd(2d), entryTolerance); } @@ -275,8 +275,8 @@ public final class SparseRealMatrixTest extends TestCase { /** test transpose */ public void testTranspose() { - - RealMatrix m = createSparseMatrix(testData); + + RealMatrix m = createSparseMatrix(testData); RealMatrix mIT = new LUDecompositionImpl(m).getSolver().getInverse().transpose(); RealMatrix mTI = new LUDecompositionImpl(m.transpose()).getSolver().getInverse(); assertClose("inverse-transpose", mIT, mTI, normTolerance); @@ -368,7 +368,7 @@ public final class SparseRealMatrixTest extends TestCase { assertEquals(2, p.getRowDimension()); assertEquals(2, p.getColumnDimension()); // Invert p - RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse(); + RealMatrix pInverse = new LUDecompositionImpl(p).getSolver().getInverse(); assertEquals(2, pInverse.getRowDimension()); assertEquals(2, pInverse.getColumnDimension()); @@ -401,17 +401,17 @@ public final class SparseRealMatrixTest extends TestCase { assertEquals("Rows23Cols00", mRows23Cols00, m.getSubMatrix(2, 3, 0, 0)); assertEquals("Rows00Cols33", mRows00Cols33, m.getSubMatrix(0, 0, 3, 3)); assertEquals("Rows01Cols23", mRows01Cols23, m.getSubMatrix(0, 1, 2, 3)); - assertEquals("Rows02Cols13", mRows02Cols13, + assertEquals("Rows02Cols13", mRows02Cols13, m.getSubMatrix(new int[] { 0, 2 }, new int[] { 1, 3 })); - assertEquals("Rows03Cols12", mRows03Cols12, + assertEquals("Rows03Cols12", mRows03Cols12, m.getSubMatrix(new int[] { 0, 3 }, new int[] { 1, 2 })); - assertEquals("Rows03Cols123", mRows03Cols123, + assertEquals("Rows03Cols123", mRows03Cols123, m.getSubMatrix(new int[] { 0, 3 }, new int[] { 1, 2, 3 })); - assertEquals("Rows20Cols123", mRows20Cols123, + assertEquals("Rows20Cols123", mRows20Cols123, m.getSubMatrix(new int[] { 2, 0 }, new int[] { 1, 2, 3 })); - assertEquals("Rows31Cols31", mRows31Cols31, + assertEquals("Rows31Cols31", mRows31Cols31, m.getSubMatrix(new int[] { 3, 1 }, new int[] { 3, 1 })); - assertEquals("Rows31Cols31", mRows31Cols31, + assertEquals("Rows31Cols31", mRows31Cols31, m.getSubMatrix(new int[] { 3, 1 }, new int[] { 3, 1 })); try { @@ -555,7 +555,7 @@ public final class SparseRealMatrixTest extends TestCase { public void testToString() { OpenMapRealMatrix m = createSparseMatrix(testData); - assertEquals("OpenMapRealMatrix{{1.0,2.0,3.0},{2.0,5.0,3.0},{1.0,0.0,8.0}}", + assertEquals("OpenMapRealMatrix{{1.0,2.0,3.0},{2.0,5.0,3.0},{1.0,0.0,8.0}}", m.toString()); m = new OpenMapRealMatrix(1, 1); assertEquals("OpenMapRealMatrix{{0.0}}", m.toString()); @@ -579,8 +579,8 @@ public final class SparseRealMatrixTest extends TestCase { assertEquals(expected, m); // javadoc example - OpenMapRealMatrix matrix = - createSparseMatrix(new double[][] { + OpenMapRealMatrix matrix = + createSparseMatrix(new double[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 0, 1, 2 } }); matrix.setSubMatrix(new double[][] { { 3, 4 }, { 5, 6 } }, 1, 1); expected = createSparseMatrix(new double[][] { @@ -664,7 +664,7 @@ public final class SparseRealMatrixTest extends TestCase { tolerance); } } - + private OpenMapRealMatrix createSparseMatrix(double[][] data) { OpenMapRealMatrix matrix = new OpenMapRealMatrix(data.length, data[0].length); for (int row = 0; row < data.length; row++) { diff --git a/src/test/java/org/apache/commons/math/linear/SparseRealVectorTest.java b/src/test/java/org/apache/commons/math/linear/SparseRealVectorTest.java index 2112e6021..d55c90c2b 100644 --- a/src/test/java/org/apache/commons/math/linear/SparseRealVectorTest.java +++ b/src/test/java/org/apache/commons/math/linear/SparseRealVectorTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,7 +31,7 @@ import org.apache.commons.math.TestUtils; */ public class SparseRealVectorTest extends TestCase { - // + // protected double[][] ma1 = {{1d, 2d, 3d}, {4d, 5d, 6d}, {7d, 8d, 9d}}; protected double[] vec1 = {1d, 2d, 3d}; protected double[] vec2 = {4d, 5d, 6d}; @@ -45,7 +45,7 @@ public class SparseRealVectorTest extends TestCase { protected double entryTolerance = 10E-16; protected double normTolerance = 10E-14; - // Testclass to test the RealVector interface + // Testclass to test the RealVector interface // only with enough content to support the test public static class SparseRealVectorTestImpl implements RealVector, Serializable { @@ -521,7 +521,7 @@ public class SparseRealVectorTest extends TestCase { OpenMapRealVector v1 = new OpenMapRealVector(vec1); OpenMapRealVector v2 = new OpenMapRealVector(vec2); OpenMapRealVector v4 = new OpenMapRealVector(vec4); - SparseRealVectorTestImpl v2_t = new SparseRealVectorTestImpl(vec2); + SparseRealVectorTestImpl v2_t = new SparseRealVectorTestImpl(vec2); RealVector v_append_1 = v1.append(v2); assertEquals("testData len", 6, v_append_1.getDimension()); @@ -538,7 +538,7 @@ public class SparseRealVectorTest extends TestCase { RealVector v_append_4 = v1.append(v2_t); assertEquals("testData len", 6, v_append_4.getDimension()); assertEquals("testData is 4.0 ", 4.0, v_append_4.getEntry(3)); - + RealVector vout5 = v4.getSubVector(3, 3); assertEquals("testData len", 3, vout5.getDimension()); assertEquals("testData is 4.0 ", 5.0, vout5.getEntry(1)); @@ -605,7 +605,7 @@ public class SparseRealVectorTest extends TestCase { } - public void testMapFunctions() { + public void testMapFunctions() { OpenMapRealVector v1 = new OpenMapRealVector(vec1); //octave = v1 .+ 2.0 @@ -806,7 +806,7 @@ public class SparseRealVectorTest extends TestCase { //octave = asin(vat) RealVector v_mapAsinToSelf = vat.copy(); - v_mapAsinToSelf.mapAsinToSelf(); + v_mapAsinToSelf.mapAsinToSelf(); double[] result_mapAsinToSelf = {0.0d,5.235987755982989e-01d,1.570796326794897e+00d}; assertClose("compare vectors" ,result_mapAsinToSelf,v_mapAsinToSelf.getData(),normTolerance); @@ -933,12 +933,12 @@ public class SparseRealVectorTest extends TestCase { } - public void testBasicFunctions() { + public void testBasicFunctions() { OpenMapRealVector v1 = new OpenMapRealVector(vec1); OpenMapRealVector v2 = new OpenMapRealVector(vec2); OpenMapRealVector v_null = new OpenMapRealVector(vec_null); - SparseRealVectorTestImpl v2_t = new SparseRealVectorTestImpl(vec2); + SparseRealVectorTestImpl v2_t = new SparseRealVectorTestImpl(vec2); //octave = sqrt(sumsq(v1)) double d_getNorm = v1.getNorm(); @@ -1024,7 +1024,7 @@ public class SparseRealVectorTest extends TestCase { assertEquals("compare val ",4d, m_outerProduct_2.getEntry(0,0)); RealVector v_unitVector = v1.unitVector(); - RealVector v_unitVector_2 = v1.mapDivide(v1.getNorm()); + RealVector v_unitVector_2 = v1.mapDivide(v1.getNorm()); assertClose("compare vect" ,v_unitVector.getData(),v_unitVector_2.getData(),normTolerance); try { @@ -1056,21 +1056,21 @@ public class SparseRealVectorTest extends TestCase { double[] result_projection_2 = {1.662337662337662, 2.0779220779220777, 2.493506493506493}; assertClose("compare vect", v_projection_2.getData(), result_projection_2, normTolerance); - } + } - public void testMisc() { + public void testMisc() { OpenMapRealVector v1 = new OpenMapRealVector(vec1); String out1 = v1.toString(); assertTrue("some output ", out1.length()!=0); try { - v1.checkVectorDimensions(2); + v1.checkVectorDimensions(2); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); - } + } } @@ -1100,7 +1100,7 @@ public class SparseRealVectorTest extends TestCase { OpenMapRealVector v = new OpenMapRealVector(new double[] { 0, 1, 2 }); assertEquals(v,TestUtils.serializeAndRecover(v)); } - + /** verifies that two vectors are close (sup norm) */ protected void assertClose(String msg, double[] m, double[] n, double tolerance) { diff --git a/src/test/java/org/apache/commons/math/linear/TriDiagonalTransformerTest.java b/src/test/java/org/apache/commons/math/linear/TriDiagonalTransformerTest.java index e178c3432..81ad42137 100644 --- a/src/test/java/org/apache/commons/math/linear/TriDiagonalTransformerTest.java +++ b/src/test/java/org/apache/commons/math/linear/TriDiagonalTransformerTest.java @@ -106,7 +106,7 @@ public class TriDiagonalTransformerTest extends TestCase { private void checkOrthogonal(RealMatrix m) { RealMatrix mTm = m.transpose().multiply(m); RealMatrix id = MatrixUtils.createRealIdentityMatrix(mTm.getRowDimension()); - assertEquals(0, mTm.subtract(id).getNorm(), 1.0e-15); + assertEquals(0, mTm.subtract(id).getNorm(), 1.0e-15); } public void testTTriDiagonal() { @@ -121,7 +121,7 @@ public class TriDiagonalTransformerTest extends TestCase { for (int j = 0; j < cols; ++j) { if ((i < j - 1) || (i > j + 1)) { assertEquals(0, m.getEntry(i, j), 1.0e-16); - } + } } } } @@ -176,7 +176,7 @@ public class TriDiagonalTransformerTest extends TestCase { // check the same cached instance is returned the second time assertTrue(q == transformer.getQ()); assertTrue(t == transformer.getT()); - + } public static Test suite() { diff --git a/src/test/java/org/apache/commons/math/ode/ContinuousOutputModelTest.java b/src/test/java/org/apache/commons/math/ode/ContinuousOutputModelTest.java index 243f4d6eb..6496577e3 100644 --- a/src/test/java/org/apache/commons/math/ode/ContinuousOutputModelTest.java +++ b/src/test/java/org/apache/commons/math/ode/ContinuousOutputModelTest.java @@ -128,7 +128,7 @@ public class ContinuousOutputModelTest assertEquals(Math.cos(t), y[0], 1.0e-7); assertEquals(Math.sin(t), y[1], 1.0e-7); } - + } public void testErrorConditions() @@ -136,7 +136,7 @@ public class ContinuousOutputModelTest ContinuousOutputModel cm = new ContinuousOutputModel(); cm.handleStep(buildInterpolator(0, new double[] { 0.0, 1.0, -2.0 }, 1), true); - + // dimension mismatch assertTrue(checkAppendError(cm, 1.0, new double[] { 0.0, 1.0 }, 2.0)); diff --git a/src/test/java/org/apache/commons/math/ode/FirstOrderConverterTest.java b/src/test/java/org/apache/commons/math/ode/FirstOrderConverterTest.java index 14e3ca01b..98ff66140 100644 --- a/src/test/java/org/apache/commons/math/ode/FirstOrderConverterTest.java +++ b/src/test/java/org/apache/commons/math/ode/FirstOrderConverterTest.java @@ -39,10 +39,10 @@ public class FirstOrderConverterTest assertTrue(eqn1.getDimension() == (2 * eqn2.getDimension())); } } - + public void testDecreasingSteps() throws DerivativeException, IntegratorException { - + double previousError = Double.NaN; for (int i = 0; i < 10; ++i) { @@ -53,7 +53,7 @@ public class FirstOrderConverterTest assertTrue(Math.abs(error) < Math.abs(previousError)); } previousError = error; - + } } @@ -70,34 +70,34 @@ public class FirstOrderConverterTest - Math.sin(4.0); assertTrue(Math.abs(error) > 0.1); } - + public static Test suite() { return new TestSuite(FirstOrderConverterTest.class); } private static class Equations implements SecondOrderDifferentialEquations { - + private int n; private double omega2; - + public Equations(int n, double omega) { this.n = n; omega2 = omega * omega; } - + public int getDimension() { return n; } - + public void computeSecondDerivatives(double t, double[] y, double[] yDot, double[] yDDot) { for (int i = 0; i < n; ++i) { yDDot[i] = -omega2 * y[i]; } } - + } private double integrateWithSpecifiedStep(double omega, diff --git a/src/test/java/org/apache/commons/math/ode/TestProblem1.java b/src/test/java/org/apache/commons/math/ode/TestProblem1.java index 0e64548cf..1143e8e30 100644 --- a/src/test/java/org/apache/commons/math/ode/TestProblem1.java +++ b/src/test/java/org/apache/commons/math/ode/TestProblem1.java @@ -52,7 +52,7 @@ public class TestProblem1 setErrorScale(errorScale); y = new double[y0.length]; } - + /** * Copy constructor. * @param problem problem to copy diff --git a/src/test/java/org/apache/commons/math/ode/TestProblem2.java b/src/test/java/org/apache/commons/math/ode/TestProblem2.java index 9e2cf20cc..ebcbe571c 100644 --- a/src/test/java/org/apache/commons/math/ode/TestProblem2.java +++ b/src/test/java/org/apache/commons/math/ode/TestProblem2.java @@ -53,7 +53,7 @@ public class TestProblem2 setErrorScale(errorScale); y = new double[y0.length]; } - + /** * Copy constructor. * @param problem problem to copy diff --git a/src/test/java/org/apache/commons/math/ode/TestProblem3.java b/src/test/java/org/apache/commons/math/ode/TestProblem3.java index 7a988609e..846f7e241 100644 --- a/src/test/java/org/apache/commons/math/ode/TestProblem3.java +++ b/src/test/java/org/apache/commons/math/ode/TestProblem3.java @@ -60,14 +60,14 @@ public class TestProblem3 setErrorScale(errorScale); y = new double[y0.length]; } - + /** * Simple constructor. */ public TestProblem3() { this(0.1); } - + /** * Copy constructor. * @param problem problem to copy diff --git a/src/test/java/org/apache/commons/math/ode/TestProblem4.java b/src/test/java/org/apache/commons/math/ode/TestProblem4.java index ba24cec11..1ae13c9dd 100644 --- a/src/test/java/org/apache/commons/math/ode/TestProblem4.java +++ b/src/test/java/org/apache/commons/math/ode/TestProblem4.java @@ -57,7 +57,7 @@ public class TestProblem4 setErrorScale(errorScale); y = new double[y0.length]; } - + /** * Copy constructor. * @param problem problem to copy @@ -111,7 +111,7 @@ public class TestProblem4 sign = -sign; return EventHandler.RESET_STATE; } - + public void resetState(double t, double[] y) { y[0] = -y[0]; y[1] = -y[1]; @@ -133,7 +133,7 @@ public class TestProblem4 public int eventOccurred(double t, double[] y, boolean increasing) { return EventHandler.STOP; } - + public void resetState(double t, double[] y) { } diff --git a/src/test/java/org/apache/commons/math/ode/TestProblemAbstract.java b/src/test/java/org/apache/commons/math/ode/TestProblemAbstract.java index c6d4bb901..69d55f087 100644 --- a/src/test/java/org/apache/commons/math/ode/TestProblemAbstract.java +++ b/src/test/java/org/apache/commons/math/ode/TestProblemAbstract.java @@ -96,7 +96,7 @@ public abstract class TestProblemAbstract calls = 0; n = y0.length; this.t0 = t0; - this.y0 = y0.clone(); + this.y0 = y0.clone(); } /** @@ -112,7 +112,7 @@ public abstract class TestProblemAbstract * @param errorScale error scale */ protected void setErrorScale(double[] errorScale) { - this.errorScale = errorScale.clone(); + this.errorScale = errorScale.clone(); } public int getDimension() { diff --git a/src/test/java/org/apache/commons/math/ode/nonstiff/ClassicalRungeKuttaIntegratorTest.java b/src/test/java/org/apache/commons/math/ode/nonstiff/ClassicalRungeKuttaIntegratorTest.java index cd23aff05..962c10a13 100644 --- a/src/test/java/org/apache/commons/math/ode/nonstiff/ClassicalRungeKuttaIntegratorTest.java +++ b/src/test/java/org/apache/commons/math/ode/nonstiff/ClassicalRungeKuttaIntegratorTest.java @@ -73,10 +73,10 @@ public class ClassicalRungeKuttaIntegratorTest } catch(IntegratorException ie) { } } - + public void testDecreasingSteps() throws DerivativeException, IntegratorException { - + TestProblemAbstract[] problems = TestProblemFactory.getProblems(); for (int k = 0; k < problems.length; ++k) { @@ -231,7 +231,7 @@ public class ClassicalRungeKuttaIntegratorTest return false; } public void reset() { - } + } }); integ.integrate(new FirstOrderDifferentialEquations() { private static final long serialVersionUID = 0L; diff --git a/src/test/java/org/apache/commons/math/ode/nonstiff/DormandPrince54IntegratorTest.java b/src/test/java/org/apache/commons/math/ode/nonstiff/DormandPrince54IntegratorTest.java index 71aa95ef0..15e82ae57 100644 --- a/src/test/java/org/apache/commons/math/ode/nonstiff/DormandPrince54IntegratorTest.java +++ b/src/test/java/org/apache/commons/math/ode/nonstiff/DormandPrince54IntegratorTest.java @@ -352,7 +352,7 @@ public class DormandPrince54IntegratorTest assertTrue(minStep < (1.0 / 450.0)); assertTrue(maxStep > (1.0 / 4.2)); } - } + } private boolean firstTime; private double minStep; private double maxStep; diff --git a/src/test/java/org/apache/commons/math/ode/nonstiff/EulerIntegratorTest.java b/src/test/java/org/apache/commons/math/ode/nonstiff/EulerIntegratorTest.java index ac4fb7a06..a47537a30 100644 --- a/src/test/java/org/apache/commons/math/ode/nonstiff/EulerIntegratorTest.java +++ b/src/test/java/org/apache/commons/math/ode/nonstiff/EulerIntegratorTest.java @@ -52,7 +52,7 @@ public class EulerIntegratorTest } catch(IntegratorException ie) { } } - + public void testDecreasingSteps() throws DerivativeException, IntegratorException { @@ -166,7 +166,7 @@ public class EulerIntegratorTest return false; } public void reset() { - } + } }); integ.integrate(new FirstOrderDifferentialEquations() { private static final long serialVersionUID = 0L; diff --git a/src/test/java/org/apache/commons/math/ode/nonstiff/EulerStepInterpolatorTest.java b/src/test/java/org/apache/commons/math/ode/nonstiff/EulerStepInterpolatorTest.java index 610dc0b18..ea38d3fcc 100644 --- a/src/test/java/org/apache/commons/math/ode/nonstiff/EulerStepInterpolatorTest.java +++ b/src/test/java/org/apache/commons/math/ode/nonstiff/EulerStepInterpolatorTest.java @@ -145,7 +145,7 @@ public class EulerStepInterpolatorTest { for (StepHandler handler : integ.getStepHandlers()) { oos.writeObject(handler); } - + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); ContinuousOutputModel cm = (ContinuousOutputModel) ois.readObject(); @@ -171,7 +171,7 @@ public class EulerStepInterpolatorTest { private static class DummyIntegrator extends RungeKuttaIntegrator { - + protected DummyIntegrator(RungeKuttaStepInterpolator prototype) { super("dummy", new double[0], new double[0][0], new double[0], prototype, Double.NaN); } diff --git a/src/test/java/org/apache/commons/math/ode/nonstiff/GillIntegratorTest.java b/src/test/java/org/apache/commons/math/ode/nonstiff/GillIntegratorTest.java index fce8de0cb..743b89280 100644 --- a/src/test/java/org/apache/commons/math/ode/nonstiff/GillIntegratorTest.java +++ b/src/test/java/org/apache/commons/math/ode/nonstiff/GillIntegratorTest.java @@ -53,10 +53,10 @@ public class GillIntegratorTest } catch(IntegratorException ie) { } } - + public void testDecreasingSteps() throws DerivativeException, IntegratorException { - + TestProblemAbstract[] problems = TestProblemFactory.getProblems(); for (int k = 0; k < problems.length; ++k) { @@ -221,7 +221,7 @@ public class GillIntegratorTest return false; } public void reset() { - } + } }); integ.integrate(new FirstOrderDifferentialEquations() { private static final long serialVersionUID = 0L; diff --git a/src/test/java/org/apache/commons/math/ode/nonstiff/HighamHall54IntegratorTest.java b/src/test/java/org/apache/commons/math/ode/nonstiff/HighamHall54IntegratorTest.java index b041aec2f..f16fcc670 100644 --- a/src/test/java/org/apache/commons/math/ode/nonstiff/HighamHall54IntegratorTest.java +++ b/src/test/java/org/apache/commons/math/ode/nonstiff/HighamHall54IntegratorTest.java @@ -79,7 +79,7 @@ public class HighamHall54IntegratorTest } } catch (Exception e) { - fail("wrong exception caught: " + e.getMessage()); + fail("wrong exception caught: " + e.getMessage()); } } diff --git a/src/test/java/org/apache/commons/math/ode/nonstiff/MidpointIntegratorTest.java b/src/test/java/org/apache/commons/math/ode/nonstiff/MidpointIntegratorTest.java index 8e35e6a96..35a84e829 100644 --- a/src/test/java/org/apache/commons/math/ode/nonstiff/MidpointIntegratorTest.java +++ b/src/test/java/org/apache/commons/math/ode/nonstiff/MidpointIntegratorTest.java @@ -52,10 +52,10 @@ public class MidpointIntegratorTest } catch(IntegratorException ie) { } } - + public void testDecreasingSteps() throws DerivativeException, IntegratorException { - + TestProblemAbstract[] problems = TestProblemFactory.getProblems(); for (int k = 0; k < problems.length; ++k) { @@ -166,7 +166,7 @@ public class MidpointIntegratorTest return false; } public void reset() { - } + } }); integ.integrate(new FirstOrderDifferentialEquations() { private static final long serialVersionUID = 0L; diff --git a/src/test/java/org/apache/commons/math/ode/nonstiff/ThreeEighthesIntegratorTest.java b/src/test/java/org/apache/commons/math/ode/nonstiff/ThreeEighthesIntegratorTest.java index 40a7ef360..f91fa340f 100644 --- a/src/test/java/org/apache/commons/math/ode/nonstiff/ThreeEighthesIntegratorTest.java +++ b/src/test/java/org/apache/commons/math/ode/nonstiff/ThreeEighthesIntegratorTest.java @@ -53,13 +53,13 @@ public class ThreeEighthesIntegratorTest } catch(IntegratorException ie) { } } - + public void testDecreasingSteps() throws DerivativeException, IntegratorException { - + TestProblemAbstract[] problems = TestProblemFactory.getProblems(); for (int k = 0; k < problems.length; ++k) { - + double previousError = Double.NaN; for (int i = 4; i < 10; ++i) { @@ -217,7 +217,7 @@ public class ThreeEighthesIntegratorTest return false; } public void reset() { - } + } }); integ.integrate(new FirstOrderDifferentialEquations() { public void computeDerivatives(double t, double[] y, double[] dot) { diff --git a/src/test/java/org/apache/commons/math/optimization/MultiStartDifferentiableMultivariateVectorialOptimizerTest.java b/src/test/java/org/apache/commons/math/optimization/MultiStartDifferentiableMultivariateVectorialOptimizerTest.java index 68b5f1802..68c0b64f4 100644 --- a/src/test/java/org/apache/commons/math/optimization/MultiStartDifferentiableMultivariateVectorialOptimizerTest.java +++ b/src/test/java/org/apache/commons/math/optimization/MultiStartDifferentiableMultivariateVectorialOptimizerTest.java @@ -38,7 +38,7 @@ import org.junit.Test; /** *

      Some of the unit tests are re-implementations of the MINPACK file17 and file22 test files. + * href="http://www.netlib.org/minpack/ex/file22">file22 test files. * The redistribution policy for MINPACK is available here, for * convenience, it is reproduced below.

      diff --git a/src/test/java/org/apache/commons/math/optimization/direct/MultiDirectionalTest.java b/src/test/java/org/apache/commons/math/optimization/direct/MultiDirectionalTest.java index 71f6ecb9b..a4e156ebb 100644 --- a/src/test/java/org/apache/commons/math/optimization/direct/MultiDirectionalTest.java +++ b/src/test/java/org/apache/commons/math/optimization/direct/MultiDirectionalTest.java @@ -53,7 +53,7 @@ public class MultiDirectionalTest { Assert.assertNull(ce.getCause()); } catch (Exception e) { Assert.fail("wrong exception caught: " + e.getMessage()); - } + } try { MultiDirectional optimizer = new MultiDirectional(0.9, 1.9); optimizer.optimize(wrong, GoalType.MINIMIZE, new double[] { +2.0 }); @@ -63,7 +63,7 @@ public class MultiDirectionalTest { Assert.assertNotNull(ce.getCause()); } catch (Exception e) { Assert.fail("wrong exception caught: " + e.getMessage()); - } + } } @Test @@ -105,7 +105,7 @@ public class MultiDirectionalTest { optimum = optimizer.optimize(fourExtrema, GoalType.MINIMIZE, new double[] { +1, 0 }); Assert.assertEquals(xP, optimum.getPoint()[0], 2.0e-8); Assert.assertEquals(yM, optimum.getPoint()[1], 3.0e-6); - Assert.assertEquals(valueXpYm, optimum.getValue(), 2.0e-12); + Assert.assertEquals(valueXpYm, optimum.getValue(), 2.0e-12); Assert.assertTrue(optimizer.getEvaluations() > 120); Assert.assertTrue(optimizer.getEvaluations() < 150); @@ -213,7 +213,7 @@ public class MultiDirectionalTest { final double[] actualPosition = estimate.getPoint(); Assert.assertEquals(expectedPosition[0], actualPosition[0], EPSILON ); Assert.assertEquals(expectedPosition[1], actualPosition[1], EPSILON ); - + } private static class Gaussian2D implements MultivariateRealFunction { @@ -221,7 +221,7 @@ public class MultiDirectionalTest { private final double[] maximumPosition; private final double std; - + public Gaussian2D(double xOpt, double yOpt, double std) { maximumPosition = new double[] { xOpt, yOpt }; this.std = std; diff --git a/src/test/java/org/apache/commons/math/optimization/direct/NelderMeadTest.java b/src/test/java/org/apache/commons/math/optimization/direct/NelderMeadTest.java index 6ec68c807..ee611891a 100644 --- a/src/test/java/org/apache/commons/math/optimization/direct/NelderMeadTest.java +++ b/src/test/java/org/apache/commons/math/optimization/direct/NelderMeadTest.java @@ -66,7 +66,7 @@ public class NelderMeadTest { assertNull(ce.getCause()); } catch (Exception e) { fail("wrong exception caught: " + e.getMessage()); - } + } try { NelderMead optimizer = new NelderMead(0.9, 1.9, 0.4, 0.6); optimizer.optimize(wrong, GoalType.MINIMIZE, new double[] { +2.0 }); @@ -76,7 +76,7 @@ public class NelderMeadTest { assertNotNull(ce.getCause()); } catch (Exception e) { fail("wrong exception caught: " + e.getMessage()); - } + } } @Test @@ -118,7 +118,7 @@ public class NelderMeadTest { optimum = optimizer.optimize(fourExtrema, GoalType.MINIMIZE, new double[] { +1, 0 }); assertEquals(xP, optimum.getPoint()[0], 5.0e-6); assertEquals(yM, optimum.getPoint()[1], 6.0e-6); - assertEquals(valueXpYm, optimum.getValue(), 1.0e-11); + assertEquals(valueXpYm, optimum.getValue(), 1.0e-11); assertTrue(optimizer.getEvaluations() > 60); assertTrue(optimizer.getEvaluations() < 90); diff --git a/src/test/java/org/apache/commons/math/optimization/fitting/HarmonicFitterTest.java b/src/test/java/org/apache/commons/math/optimization/fitting/HarmonicFitterTest.java index 741b35988..35bd0e682 100644 --- a/src/test/java/org/apache/commons/math/optimization/fitting/HarmonicFitterTest.java +++ b/src/test/java/org/apache/commons/math/optimization/fitting/HarmonicFitterTest.java @@ -5,9 +5,9 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/src/test/java/org/apache/commons/math/optimization/fitting/PolynomialFitterTest.java b/src/test/java/org/apache/commons/math/optimization/fitting/PolynomialFitterTest.java index 1c86b2617..a2632f587 100644 --- a/src/test/java/org/apache/commons/math/optimization/fitting/PolynomialFitterTest.java +++ b/src/test/java/org/apache/commons/math/optimization/fitting/PolynomialFitterTest.java @@ -5,9 +5,9 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/src/test/java/org/apache/commons/math/optimization/general/GaussNewtonOptimizerTest.java b/src/test/java/org/apache/commons/math/optimization/general/GaussNewtonOptimizerTest.java index 469a79a15..622f84b9c 100644 --- a/src/test/java/org/apache/commons/math/optimization/general/GaussNewtonOptimizerTest.java +++ b/src/test/java/org/apache/commons/math/optimization/general/GaussNewtonOptimizerTest.java @@ -39,7 +39,7 @@ import org.apache.commons.math.optimization.VectorialPointValuePair; /** *

      Some of the unit tests are re-implementations of the MINPACK file17 and file22 test files. + * href="http://www.netlib.org/minpack/ex/file22">file22 test files. * The redistribution policy for MINPACK is available here, for * convenience, it is reproduced below.

      @@ -551,8 +551,8 @@ extends TestCase { for (int i = 0; i < n; ++i) { Point2D.Double pi = points.get(i); double di = pi.distance(center); - jacobian[i][0] = (center.x - pi.x) / di - dRdX; - jacobian[i][1] = (center.y - pi.y) / di - dRdY; + jacobian[i][0] = (center.x - pi.x) / di - dRdX; + jacobian[i][1] = (center.y - pi.y) / di - dRdY; } return jacobian; diff --git a/src/test/java/org/apache/commons/math/optimization/general/LevenbergMarquardtOptimizerTest.java b/src/test/java/org/apache/commons/math/optimization/general/LevenbergMarquardtOptimizerTest.java index c532ecd7f..964481641 100644 --- a/src/test/java/org/apache/commons/math/optimization/general/LevenbergMarquardtOptimizerTest.java +++ b/src/test/java/org/apache/commons/math/optimization/general/LevenbergMarquardtOptimizerTest.java @@ -39,7 +39,7 @@ import org.apache.commons.math.optimization.VectorialPointValuePair; /** *

      Some of the unit tests are re-implementations of the MINPACK file17 and file22 test files. + * href="http://www.netlib.org/minpack/ex/file22">file22 test files. * The redistribution policy for MINPACK is available here, for * convenience, it is reproduced below.

      @@ -210,7 +210,7 @@ public class LevenbergMarquardtOptimizerTest { 2, 1, 3 }, { -3, 0, -9 } }, new double[] { 1, 1, 1 }); - + LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(); optimizer.optimize(problem, problem.target, new double[] { 1, 1, 1 }, new double[] { 0, 0, 0 }); assertTrue(Math.sqrt(problem.target.length) * optimizer.getRMS() > 0.6); @@ -590,8 +590,8 @@ public class LevenbergMarquardtOptimizerTest for (int i = 0; i < n; ++i) { Point2D.Double pi = points.get(i); double di = pi.distance(center); - jacobian[i][0] = (center.x - pi.x) / di - dRdX; - jacobian[i][1] = (center.y - pi.y) / di - dRdY; + jacobian[i][0] = (center.x - pi.x) / di - dRdX; + jacobian[i][1] = (center.y - pi.y) / di - dRdY; } return jacobian; diff --git a/src/test/java/org/apache/commons/math/optimization/general/MinpackTest.java b/src/test/java/org/apache/commons/math/optimization/general/MinpackTest.java index d5cac581b..5c3c14bd0 100644 --- a/src/test/java/org/apache/commons/math/optimization/general/MinpackTest.java +++ b/src/test/java/org/apache/commons/math/optimization/general/MinpackTest.java @@ -33,7 +33,7 @@ import org.apache.commons.math.optimization.VectorialPointValuePair; /** *

      Some of the unit tests are re-implementations of the MINPACK file17 and file22 test files. + * href="http://www.netlib.org/minpack/ex/file22">file22 test files. * The redistribution policy for MINPACK is available here, for * convenience, it is reproduced below.

      @@ -134,7 +134,7 @@ public class MinpackTest extends TestCase { minpackTest(new HelicalValleyFunction(new double[] { -100.0, 0.0, 0.0}, 991.261822123701), false); } - + public void testMinpackPowellSingular() { minpackTest(new PowellSingularFunction(new double[] { 3.0, -1.0, 0.0, 1.0 }, 14.6628782986152), false); @@ -143,7 +143,7 @@ public class MinpackTest extends TestCase { minpackTest(new PowellSingularFunction(new double[] { 300.0, -100.0, 0.0, 100.0 }, 126887.903284750), false); } - + public void testMinpackFreudensteinRoth() { minpackTest(new FreudensteinRothFunction(new double[] { 0.5, -2.0 }, 20.0124960961895, 6.99887517584575, @@ -164,7 +164,7 @@ public class MinpackTest extends TestCase { -0.89680510749204 }), false); } - + public void testMinpackBard() { minpackTest(new BardFunction(1.0, 6.45613629515967, 0.0906359603390466, new double[] { @@ -185,7 +185,7 @@ public class MinpackTest extends TestCase { -164464906.857771 }), false); } - + public void testMinpackKowalikOsborne() { minpackTest(new KowalikOsborneFunction(new double[] { 0.25, 0.39, 0.415, 0.39 }, 0.0728915102882945, @@ -215,7 +215,7 @@ public class MinpackTest extends TestCase { 0.134575665392506 }), false); } - + public void testMinpackMeyer() { minpackTest(new MeyerFunction(new double[] { 0.02, 4000.0, 250.0 }, 41153.4665543031, 9.37794514651874, @@ -232,9 +232,9 @@ public class MinpackTest extends TestCase { 901.268527953801 }), true); } - + public void testMinpackWatson() { - + minpackTest(new WatsonFunction(6, 0.0, 5.47722557505166, 0.0478295939097601, new double[] { @@ -317,12 +317,12 @@ public class MinpackTest extends TestCase { }), false); } - + public void testMinpackBox3Dimensional() { minpackTest(new Box3DimensionalFunction(10, new double[] { 0.0, 10.0, 20.0 }, 32.1115837449572), false); } - + public void testMinpackJennrichSampson() { minpackTest(new JennrichSampsonFunction(10, new double[] { 0.3, 0.4 }, 64.5856498144943, 11.1517793413499, @@ -354,7 +354,7 @@ public class MinpackTest extends TestCase { -0.403688070279258, 0.236665033746463 }), false); } - + public void testMinpackChebyquad() { minpackTest(new ChebyquadFunction(1, 8, 1.0, 1.88623796907732, 1.88623796907732, @@ -392,7 +392,7 @@ public class MinpackTest extends TestCase { 0.833291216194063, 0.940379732824644 }), false); } - + public void testMinpackBrownAlmostLinear() { minpackTest(new BrownAlmostLinearFunction(10, 0.5, 16.5302162063499, 0.0, @@ -411,7 +411,7 @@ public class MinpackTest extends TestCase { 0.979430303349865, 0.979430303349865, 0.979430303349865, 0.979430303349865, 0.979430303349865, 1.20569696650135 - }), false); + }), false); minpackTest(new BrownAlmostLinearFunction(10, 50.0, 0.9765625e17, 0.0, new double[] { @@ -460,7 +460,7 @@ public class MinpackTest extends TestCase { 0.999999999999121 }), false); } - + public void testMinpackOsborne1() { minpackTest(new Osborne1Function(new double[] { 0.5, 1.5, -1.0, 0.01, 0.02, }, 0.937564021037838, 0.00739249260904843, @@ -470,9 +470,9 @@ public class MinpackTest extends TestCase { 0.0221227011813076 }), false); } - + public void testMinpackOsborne2() { - + minpackTest(new Osborne2Function(new double[] { 1.3, 0.65, 0.65, 0.7, 0.6, 3.0, 5.0, 7.0, 2.0, 4.5, 5.5 @@ -512,7 +512,7 @@ public class MinpackTest extends TestCase { private static abstract class MinpackFunction implements DifferentiableMultivariateVectorialFunction, Serializable { - + private static final long serialVersionUID = -6209760235478794233L; protected int n; protected int m; @@ -1025,7 +1025,7 @@ public class MinpackTest extends TestCase { 34780.0, 28610.0, 23650.0, 19630.0, 16370.0, 13720.0, 11540.0, 9744.0, 8261.0, 7030.0, 6005.0, 5147.0, - 4427.0, 3820.0, 3307.0, 2872.0 + 4427.0, 3820.0, 3307.0, 2872.0 }; } diff --git a/src/test/java/org/apache/commons/math/optimization/general/NonLinearConjugateGradientOptimizerTest.java b/src/test/java/org/apache/commons/math/optimization/general/NonLinearConjugateGradientOptimizerTest.java index 1cf1e7794..19793f8aa 100644 --- a/src/test/java/org/apache/commons/math/optimization/general/NonLinearConjugateGradientOptimizerTest.java +++ b/src/test/java/org/apache/commons/math/optimization/general/NonLinearConjugateGradientOptimizerTest.java @@ -40,7 +40,7 @@ import org.apache.commons.math.optimization.SimpleScalarValueChecker; /** *

      Some of the unit tests are re-implementations of the MINPACK file17 and file22 test files. + * href="http://www.netlib.org/minpack/ex/file22">file22 test files. * The redistribution policy for MINPACK is available here, for * convenience, it is reproduced below.

      diff --git a/src/test/java/org/apache/commons/math/optimization/linear/SimplexSolverTest.java b/src/test/java/org/apache/commons/math/optimization/linear/SimplexSolverTest.java index 0adbbd019..584d42d50 100644 --- a/src/test/java/org/apache/commons/math/optimization/linear/SimplexSolverTest.java +++ b/src/test/java/org/apache/commons/math/optimization/linear/SimplexSolverTest.java @@ -41,7 +41,7 @@ public class SimplexSolverTest { SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); - + assertEquals(0.0, solution.getPoint()[0], .0000001); assertEquals(1.0, solution.getPoint()[1], .0000001); assertEquals(1.0, solution.getPoint()[2], .0000001); @@ -121,7 +121,7 @@ public class SimplexSolverTest { assertEquals(10.0, solution.getPoint()[0], 0.0); assertEquals(30.0, solution.getValue(), 0.0); } - + /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. @@ -227,7 +227,7 @@ public class SimplexSolverTest { assertEquals(0.0, solution.getPoint()[2], 0.0); assertEquals(15.0, solution.getValue(), 0.0); } - + @Test public void testTrivialModel() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); @@ -365,7 +365,7 @@ public class SimplexSolverTest { RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(7518.0, solution.getValue(), .0000001); } - + /** * Converts a test string to a {@link LinearConstraint}. * Ex: x0 + x1 + x2 + x3 - x12 = 0 diff --git a/src/test/java/org/apache/commons/math/optimization/linear/SimplexTableauTest.java b/src/test/java/org/apache/commons/math/optimization/linear/SimplexTableauTest.java index 59811a8a8..f45fcc72a 100644 --- a/src/test/java/org/apache/commons/math/optimization/linear/SimplexTableauTest.java +++ b/src/test/java/org/apache/commons/math/optimization/linear/SimplexTableauTest.java @@ -27,7 +27,7 @@ import junit.framework.TestCase; public class SimplexTableauTest extends TestCase { - public void testInitialization() { + public void testInitialization() { LinearObjectiveFunction f = createFunction(); Collection constraints = createConstraints(); SimplexTableau tableau = @@ -42,7 +42,7 @@ public class SimplexTableauTest extends TestCase { assertMatrixEquals(expectedInitialTableau, tableau.getData()); } - public void testdiscardArtificialVariables() { + public void testdiscardArtificialVariables() { LinearObjectiveFunction f = createFunction(); Collection constraints = createConstraints(); SimplexTableau tableau = @@ -62,7 +62,7 @@ public class SimplexTableauTest extends TestCase { Collection constraints = new ArrayList(); constraints.add(new LinearConstraint(new double[] {1, 0}, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] {0, 1}, Relationship.LEQ, 3)); - constraints.add(new LinearConstraint(new double[] {1, 1}, Relationship.LEQ, 4)); + constraints.add(new LinearConstraint(new double[] {1, 1}, Relationship.LEQ, 4)); SimplexTableau tableau = new SimplexTableau(f, constraints, GoalType.MAXIMIZE, false, 1.0e-6); double[][] initialTableau = { diff --git a/src/test/java/org/apache/commons/math/optimization/univariate/BrentMinimizerTest.java b/src/test/java/org/apache/commons/math/optimization/univariate/BrentMinimizerTest.java index 7ae5ed093..0358de428 100644 --- a/src/test/java/org/apache/commons/math/optimization/univariate/BrentMinimizerTest.java +++ b/src/test/java/org/apache/commons/math/optimization/univariate/BrentMinimizerTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,7 +31,7 @@ import org.apache.commons.math.optimization.UnivariateRealOptimizer; import org.junit.Test; /** - * @version $Revision$ $Date$ + * @version $Revision$ $Date$ */ public final class BrentMinimizerTest { diff --git a/src/test/java/org/apache/commons/math/random/AbstractRandomGeneratorTest.java b/src/test/java/org/apache/commons/math/random/AbstractRandomGeneratorTest.java index bf7503e36..9f3f4c9ac 100644 --- a/src/test/java/org/apache/commons/math/random/AbstractRandomGeneratorTest.java +++ b/src/test/java/org/apache/commons/math/random/AbstractRandomGeneratorTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,7 +19,7 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.math.stat.Frequency; - + /** * Test cases for the AbstractRandomGenerator class @@ -28,20 +28,20 @@ import org.apache.commons.math.stat.Frequency; */ public class AbstractRandomGeneratorTest extends RandomDataTest { - + protected TestRandomGenerator testGenerator = new TestRandomGenerator(); - + public AbstractRandomGeneratorTest(String name) { super(name); randomData = new RandomDataImpl(testGenerator); - } - + } + public static Test suite() { TestSuite suite = new TestSuite(AbstractRandomGeneratorTest.class); suite.setName("AbstractRandomGenerator Tests"); return suite; } - + @Override public void testNextInt() { try { @@ -55,26 +55,26 @@ public class AbstractRandomGeneratorTest extends RandomDataTest { for (int i=0; i= 0) && (value <= 3)); - freq.addValue(value); + freq.addValue(value); } long[] observed = new long[4]; for (int i=0; i<4; i++) { observed[i] = freq.getCount(i); - } - + } + /* Use ChiSquare dist with df = 4-1 = 3, alpha = .001 * Change to 11.34 for alpha = .01 */ assertTrue("chi-square test -- will fail about 1 in 1000 times", - testStatistic.chiSquare(expected,observed) < 16.27); + testStatistic.chiSquare(expected,observed) < 16.27); } - + @Override public void testNextLong() { long q1 = Long.MAX_VALUE/4; long q2 = 2 * q1; long q3 = 3 * q1; - + Frequency freq = new Frequency(); long val = 0; int value = 0; @@ -89,22 +89,22 @@ public class AbstractRandomGeneratorTest extends RandomDataTest { } else { value = 3; } - freq.addValue(value); + freq.addValue(value); } long[] observed = new long[4]; for (int i=0; i<4; i++) { observed[i] = freq.getCount(i); - } - + } + /* Use ChiSquare dist with df = 4-1 = 3, alpha = .001 * Change to 11.34 for alpha = .01 */ assertTrue("chi-square test -- will fail about 1 in 1000 times", - testStatistic.chiSquare(expected,observed) < 16.27); + testStatistic.chiSquare(expected,observed) < 16.27); } - + public void testNextBoolean() { - long halfSampleSize = smallSampleSize / 2; + long halfSampleSize = smallSampleSize / 2; double[] expected = {halfSampleSize, halfSampleSize}; long[] observed = new long[2]; for (int i=0; i - * Check that the sampleCount, mu and sigma match data in + * Test EmpiricalDistrbution.load() using sample data file.
      + * Check that the sampleCount, mu and sigma match data in * the sample data file. */ public void testLoad() throws Exception { - empiricalDistribution.load(url); + empiricalDistribution.load(url); // testData File has 10000 values, with mean ~ 5.0, std dev ~ 1 // Make sure that loaded distribution matches this assertEquals(empiricalDistribution.getSampleStats().getN(),1000,10E-7); @@ -101,12 +101,12 @@ public final class EmpiricalDistributionTest extends RetryTestCase { /** * Test EmpiricalDistrbution.load(double[]) using data taken from - * sample data file.
      - * Check that the sampleCount, mu and sigma match data in + * sample data file.
      + * Check that the sampleCount, mu and sigma match data in * the sample data file. */ public void testDoubleLoad() throws Exception { - empiricalDistribution2.load(dataArray); + empiricalDistribution2.load(dataArray); // testData File has 10000 values, with mean ~ 5.0, std dev ~ 1 // Make sure that loaded distribution matches this assertEquals(empiricalDistribution2.getSampleStats().getN(),1000,10E-7); @@ -117,14 +117,14 @@ public final class EmpiricalDistributionTest extends RetryTestCase { assertEquals (empiricalDistribution2.getSampleStats().getStandardDeviation(), 1.0173699343977738,10E-7); - + double[] bounds = empiricalDistribution2.getUpperBounds(); assertEquals(bounds.length, 100); assertEquals(bounds[99], 1.0, 10e-12); - + } - - /** + + /** * Generate 1000 random values and make sure they look OK.
      * Note that there is a non-zero (but very small) probability that * these tests will fail even if the code is working as designed. @@ -133,7 +133,7 @@ public final class EmpiricalDistributionTest extends RetryTestCase { tstGen(0.1); tstDoubleGen(0.1); } - + /** * Make sure exception thrown if digest getNext is attempted * before loading empiricalDistribution. @@ -149,17 +149,17 @@ public final class EmpiricalDistributionTest extends RetryTestCase { fail("wrong exception caught"); } } - + /** * Make sure we can handle a grid size that is too fine */ public void testGridTooFine() throws Exception { empiricalDistribution = new EmpiricalDistributionImpl(1001); - tstGen(0.1); - empiricalDistribution2 = new EmpiricalDistributionImpl(1001); + tstGen(0.1); + empiricalDistribution2 = new EmpiricalDistributionImpl(1001); tstDoubleGen(0.1); } - + /** * How about too fat? */ @@ -167,10 +167,10 @@ public final class EmpiricalDistributionTest extends RetryTestCase { empiricalDistribution = new EmpiricalDistributionImpl(1); tstGen(5); // ridiculous tolerance; but ridiculous grid size // really just checking to make sure we do not bomb - empiricalDistribution2 = new EmpiricalDistributionImpl(1); - tstDoubleGen(5); + empiricalDistribution2 = new EmpiricalDistributionImpl(1); + tstDoubleGen(5); } - + /** * Test bin index overflow problem (BZ 36450) */ @@ -178,15 +178,15 @@ public final class EmpiricalDistributionTest extends RetryTestCase { double[] x = new double[] {9474.94326071674, 2080107.8865462579}; new EmpiricalDistributionImpl().load(x); } - + public void testSerialization() { // Empty EmpiricalDistribution dist = new EmpiricalDistributionImpl(); EmpiricalDistribution dist2 = (EmpiricalDistribution) TestUtils.serializeAndRecover(dist); verifySame(dist, dist2); - + // Loaded - empiricalDistribution2.load(dataArray); + empiricalDistribution2.load(dataArray); dist2 = (EmpiricalDistribution) TestUtils.serializeAndRecover(empiricalDistribution2); verifySame(empiricalDistribution2, dist2); } @@ -238,9 +238,9 @@ public final class EmpiricalDistributionTest extends RetryTestCase { assertEquals(d1.getBinStats(), d2.getBinStats()); } } - + private void tstGen(double tolerance)throws Exception { - empiricalDistribution.load(url); + empiricalDistribution.load(url); SummaryStatistics stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { stats.addValue(empiricalDistribution.getNextValue()); @@ -251,7 +251,7 @@ public final class EmpiricalDistributionTest extends RetryTestCase { } private void tstDoubleGen(double tolerance)throws Exception { - empiricalDistribution2.load(dataArray); + empiricalDistribution2.load(dataArray); SummaryStatistics stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { stats.addValue(empiricalDistribution2.getNextValue()); diff --git a/src/test/java/org/apache/commons/math/random/MersenneTwisterTest.java b/src/test/java/org/apache/commons/math/random/MersenneTwisterTest.java index 595483fc8..66e45bbdb 100644 --- a/src/test/java/org/apache/commons/math/random/MersenneTwisterTest.java +++ b/src/test/java/org/apache/commons/math/random/MersenneTwisterTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -276,7 +276,7 @@ public class MersenneTwisterTest { 950049240l, 4173257693l, 1760124957l, 512151405l, 681175196l, 580563018l, 1169662867l, 4015033554l, 2687781101l, 699691603l, 2673494188l, 1137221356l, 123599888l, 472658308l, 1053598179l, 1012713758l, 3481064843l, 3759461013l, 3981457956l, 3830587662l, 1877191791l, 3650996736l, 988064871l, 3515461600l, - 4089077232l, 2225147448l, 1249609188l, 2643151863l, 3896204135l, 2416995901l, 1397735321l, 3460025646l + 4089077232l, 2225147448l, 1249609188l, 2643151863l, 3896204135l, 2416995901l, 1397735321l, 3460025646l }; double[] refDouble = { 0.76275443, 0.99000644, 0.98670464, 0.10143112, 0.27933125, 0.69867227, 0.94218740, 0.03427201, diff --git a/src/test/java/org/apache/commons/math/random/RandomAdaptorTest.java b/src/test/java/org/apache/commons/math/random/RandomAdaptorTest.java index a51fba284..b6a1c8212 100644 --- a/src/test/java/org/apache/commons/math/random/RandomAdaptorTest.java +++ b/src/test/java/org/apache/commons/math/random/RandomAdaptorTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,29 +26,29 @@ import java.util.Random; */ public class RandomAdaptorTest extends RandomDataTest { - + public RandomAdaptorTest(String name) { super(name); - } - + } + public static Test suite() { TestSuite suite = new TestSuite(RandomAdaptorTest.class); suite.setName("RandomAdaptor Tests"); return suite; } - + public void testAdaptor() { ConstantGenerator generator = new ConstantGenerator(); Random random = RandomAdaptor.createAdaptor(generator); checkConstant(random); RandomAdaptor randomAdaptor = new RandomAdaptor(generator); - checkConstant(randomAdaptor); + checkConstant(randomAdaptor); } - + private void checkConstant(Random random) { byte[] bytes = new byte[] {0}; random.nextBytes(bytes); - assertEquals(0, bytes[0]); + assertEquals(0, bytes[0]); assertEquals(false, random.nextBoolean()); assertEquals(0, random.nextDouble(), 0); assertEquals(0, random.nextFloat(), 0); @@ -59,18 +59,18 @@ public class RandomAdaptorTest extends RandomDataTest { random.setSeed(100); assertEquals(0, random.nextDouble(), 0); } - + /* * "Constant" generator to test Adaptor delegation. * "Powered by Eclipse ;-)" - * + * */ private static class ConstantGenerator implements RandomGenerator { - + public boolean nextBoolean() { return false; } - + public void nextBytes(byte[] bytes) { } @@ -100,7 +100,7 @@ public class RandomAdaptorTest extends RandomDataTest { public void setSeed(int seed) { } - + public void setSeed(int[] seed) { } diff --git a/src/test/java/org/apache/commons/math/random/RandomDataTest.java b/src/test/java/org/apache/commons/math/random/RandomDataTest.java index cfcd32408..745979224 100644 --- a/src/test/java/org/apache/commons/math/random/RandomDataTest.java +++ b/src/test/java/org/apache/commons/math/random/RandomDataTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,7 +27,7 @@ import org.apache.commons.math.stat.descriptive.SummaryStatistics; /** * Test cases for the RandomData class. - * + * * @version $Revision$ $Date: 2009-04-05 11:55:59 -0500 (Sun, 05 Apr * 2009) $ */ @@ -451,7 +451,7 @@ public class RandomDataTest extends RetryTestCase { /* * remove this test back soon, since it takes about 4 seconds - * + * * try { randomData.setSecureAlgorithm("SHA1PRNG","SUN"); } catch * (NoSuchProviderException ex) { ; } assertTrue("different seeds", * !hex.equals(randomData.nextSecureHexString(40))); try { @@ -459,7 +459,7 @@ public class RandomDataTest extends RetryTestCase { * fail("expecting NoSuchAlgorithmException"); } catch * (NoSuchProviderException ex) { ; } catch (NoSuchAlgorithmException * ex) { ; } - * + * * try { randomData.setSecureAlgorithm("SHA1PRNG","NOSUCHPROVIDER"); * fail("expecting NoSuchProviderException"); } catch * (NoSuchProviderException ex) { ; } diff --git a/src/test/java/org/apache/commons/math/random/TestRandomGenerator.java b/src/test/java/org/apache/commons/math/random/TestRandomGenerator.java index b70e7911f..6497604d8 100644 --- a/src/test/java/org/apache/commons/math/random/TestRandomGenerator.java +++ b/src/test/java/org/apache/commons/math/random/TestRandomGenerator.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,7 +18,7 @@ package org.apache.commons.math.random; import java.util.Random; /** - * Dummy AbstractRandomGenerator concrete subclass that just wraps a + * Dummy AbstractRandomGenerator concrete subclass that just wraps a * java.util.Random instance. Used by AbstractRandomGeneratorTest to test * default implementations in AbstractRandomGenerator. * diff --git a/src/test/java/org/apache/commons/math/random/UniformRandomGeneratorTest.java b/src/test/java/org/apache/commons/math/random/UniformRandomGeneratorTest.java index 5e199c0e1..fc6560f55 100644 --- a/src/test/java/org/apache/commons/math/random/UniformRandomGeneratorTest.java +++ b/src/test/java/org/apache/commons/math/random/UniformRandomGeneratorTest.java @@ -39,8 +39,8 @@ extends TestCase { assertEquals(0.0, StatUtils.mean(sample), 0.07); assertEquals(1.0, StatUtils.variance(sample), 0.02); } - - + + public static Test suite() { return new TestSuite(UniformRandomGeneratorTest.class); } diff --git a/src/test/java/org/apache/commons/math/random/ValueServerTest.java b/src/test/java/org/apache/commons/math/random/ValueServerTest.java index cb35bab0e..6fec713db 100644 --- a/src/test/java/org/apache/commons/math/random/ValueServerTest.java +++ b/src/test/java/org/apache/commons/math/random/ValueServerTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,7 @@ import java.net.URL; import org.apache.commons.math.RetryTestCase; import org.apache.commons.math.stat.descriptive.SummaryStatistics; - + /** * Test cases for the ValueServer class. * @@ -34,7 +34,7 @@ import org.apache.commons.math.stat.descriptive.SummaryStatistics; public final class ValueServerTest extends RetryTestCase { private ValueServer vs = new ValueServer(); - + public ValueServerTest(String name) { super(name); } @@ -44,7 +44,7 @@ public final class ValueServerTest extends RetryTestCase { vs.setMode(ValueServer.DIGEST_MODE); try { URL url = getClass().getResource("testData.txt"); - vs.setValuesFileURL(url); + vs.setValuesFileURL(url); } catch (Exception ex) { fail("malformed test URL"); } @@ -56,8 +56,8 @@ public final class ValueServerTest extends RetryTestCase { return suite; } - - /** + + /** * Generate 1000 random values and make sure they look OK.
      * Note that there is a non-zero (but very small) probability that * these tests will fail even if the code is working as designed. @@ -66,31 +66,31 @@ public final class ValueServerTest extends RetryTestCase { double next = 0.0; double tolerance = 0.1; vs.computeDistribution(); - assertTrue("empirical distribution property", + assertTrue("empirical distribution property", vs.getEmpiricalDistribution() != null); SummaryStatistics stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { next = vs.getNext(); stats.addValue(next); - } + } assertEquals("mean", 5.069831575018909, stats.getMean(), tolerance); assertEquals - ("std dev", 1.0173699343977738, stats.getStandardDeviation(), + ("std dev", 1.0173699343977738, stats.getStandardDeviation(), tolerance); - + vs.computeDistribution(500); stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { next = vs.getNext(); stats.addValue(next); - } + } assertEquals("mean", 5.069831575018909, stats.getMean(), tolerance); assertEquals - ("std dev", 1.0173699343977738, stats.getStandardDeviation(), + ("std dev", 1.0173699343977738, stats.getStandardDeviation(), tolerance); - + } - + /** * Make sure exception thrown if digest getNext is attempted * before loading empiricalDistribution. @@ -131,7 +131,7 @@ public final class ValueServerTest extends RetryTestCase { } /** - * Test ValueServer REPLAY_MODE using values in testData file.
      + * Test ValueServer REPLAY_MODE using values in testData file.
      * Check that the values 1,2,1001,1002 match data file values 1 and 2. * the sample data file. */ @@ -157,8 +157,8 @@ public final class ValueServerTest extends RetryTestCase { // make sure no NPE vs.closeReplayFile(); } - - /** + + /** * Test other ValueServer modes */ public void testModes() throws Exception { @@ -185,7 +185,7 @@ public final class ValueServerTest extends RetryTestCase { // ignored } } - + /** * Test fill */ @@ -202,7 +202,7 @@ public final class ValueServerTest extends RetryTestCase { assertEquals("fill test in place",2,v2[i],Double.MIN_VALUE); } } - + /** * Test getters to make Clover happy */ @@ -213,5 +213,5 @@ public final class ValueServerTest extends RetryTestCase { URL url = vs.getValuesFileURL(); assertEquals("valuesFileURL test","http://www.apache.org",url.toString()); } - + } diff --git a/src/test/java/org/apache/commons/math/special/BetaTest.java b/src/test/java/org/apache/commons/math/special/BetaTest.java index 01446afce..cba4938a0 100644 --- a/src/test/java/org/apache/commons/math/special/BetaTest.java +++ b/src/test/java/org/apache/commons/math/special/BetaTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -60,60 +60,60 @@ public class BetaTest extends TestCase { public void testRegularizedBetaPositivePositiveNan() { testRegularizedBeta(Double.NaN, 0.5, 1.0, Double.NaN); } - + public void testRegularizedBetaNegativePositivePositive() { testRegularizedBeta(Double.NaN, -0.5, 1.0, 2.0); } - + public void testRegularizedBetaPositiveNegativePositive() { testRegularizedBeta(Double.NaN, 0.5, -1.0, 2.0); } - + public void testRegularizedBetaPositivePositiveNegative() { testRegularizedBeta(Double.NaN, 0.5, 1.0, -2.0); } - + public void testRegularizedBetaZeroPositivePositive() { testRegularizedBeta(0.0, 0.0, 1.0, 2.0); } - + public void testRegularizedBetaPositiveZeroPositive() { testRegularizedBeta(Double.NaN, 0.5, 0.0, 2.0); } - + public void testRegularizedBetaPositivePositiveZero() { testRegularizedBeta(Double.NaN, 0.5, 1.0, 0.0); } - + public void testRegularizedBetaPositivePositivePositive() { testRegularizedBeta(0.75, 0.5, 1.0, 2.0); } - + public void testLogBetaNanPositive() { testLogBeta(Double.NaN, Double.NaN, 2.0); } - + public void testLogBetaPositiveNan() { testLogBeta(Double.NaN, 1.0, Double.NaN); } - + public void testLogBetaNegativePositive() { testLogBeta(Double.NaN, -1.0, 2.0); } - + public void testLogBetaPositiveNegative() { testLogBeta(Double.NaN, 1.0, -2.0); } - + public void testLogBetaZeroPositive() { testLogBeta(Double.NaN, 0.0, 2.0); } - + public void testLogBetaPositiveZero() { testLogBeta(Double.NaN, 1.0, 0.0); } - + public void testLogBetaPositivePositive() { testLogBeta(-0.693147180559945, 1.0, 2.0); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/math/special/ErfTest.java b/src/test/java/org/apache/commons/math/special/ErfTest.java index a94242755..c92f346e6 100644 --- a/src/test/java/org/apache/commons/math/special/ErfTest.java +++ b/src/test/java/org/apache/commons/math/special/ErfTest.java @@ -48,7 +48,7 @@ public class ErfTest extends TestCase { double actual = Erf.erf(x); double expected = 0.99; assertEquals(expected, actual, 1.0e-5); - + actual = Erf.erf(-x); expected = -expected; assertEquals(expected, actual, 1.0e-5); @@ -59,7 +59,7 @@ public class ErfTest extends TestCase { double actual = Erf.erf(x); double expected = 0.995; assertEquals(expected, actual, 1.0e-5); - + actual = Erf.erf(-x); expected = -expected; assertEquals(expected, actual, 1.0e-5); @@ -70,7 +70,7 @@ public class ErfTest extends TestCase { double actual = Erf.erf(x); double expected = 0.999; assertEquals(expected, actual, 1.0e-5); - + actual = Erf.erf(-x); expected = -expected; assertEquals(expected, actual, 1.0e-5); diff --git a/src/test/java/org/apache/commons/math/special/GammaTest.java b/src/test/java/org/apache/commons/math/special/GammaTest.java index e1d23fd33..a44ede4bf 100644 --- a/src/test/java/org/apache/commons/math/special/GammaTest.java +++ b/src/test/java/org/apache/commons/math/special/GammaTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ import junit.framework.TestCase; * @version $Revision$ $Date$ */ public class GammaTest extends TestCase { - + public GammaTest(String name) { super(name); } @@ -53,39 +53,39 @@ public class GammaTest extends TestCase { public void testRegularizedGammaPositiveNan() { testRegularizedGamma(Double.NaN, 1.0, Double.NaN); } - + public void testRegularizedGammaNegativePositive() { testRegularizedGamma(Double.NaN, -1.5, 1.0); } - + public void testRegularizedGammaPositiveNegative() { testRegularizedGamma(Double.NaN, 1.0, -1.0); } - + public void testRegularizedGammaZeroPositive() { testRegularizedGamma(Double.NaN, 0.0, 1.0); } - + public void testRegularizedGammaPositiveZero() { testRegularizedGamma(0.0, 1.0, 0.0); } - + public void testRegularizedGammaPositivePositive() { testRegularizedGamma(0.632120558828558, 1.0, 1.0); } - + public void testLogGammaNan() { testLogGamma(Double.NaN, Double.NaN); } - + public void testLogGammaNegative() { testLogGamma(Double.NaN, -1.0); } - + public void testLogGammaZero() { testLogGamma(Double.NaN, 0.0); } - + public void testLogGammaPositive() { testLogGamma(0.6931471805599457, 3.0); } diff --git a/src/test/java/org/apache/commons/math/stat/CertifiedDataTest.java b/src/test/java/org/apache/commons/math/stat/CertifiedDataTest.java index fbac44a9f..ac919443d 100644 --- a/src/test/java/org/apache/commons/math/stat/CertifiedDataTest.java +++ b/src/test/java/org/apache/commons/math/stat/CertifiedDataTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -61,20 +61,20 @@ public class CertifiedDataTest extends TestCase { SummaryStatistics u = new SummaryStatistics(); loadStats("data/PiDigits.txt", u); assertEquals("PiDigits: std", std, u.getStandardDeviation(), 1E-13); - assertEquals("PiDigits: mean", mean, u.getMean(), 1E-13); + assertEquals("PiDigits: mean", mean, u.getMean(), 1E-13); loadStats("data/Mavro.txt", u); assertEquals("Mavro: std", std, u.getStandardDeviation(), 1E-14); assertEquals("Mavro: mean", mean, u.getMean(), 1E-14); - + loadStats("data/Michelso.txt", u); assertEquals("Michelso: std", std, u.getStandardDeviation(), 1E-13); - assertEquals("Michelso: mean", mean, u.getMean(), 1E-13); - + assertEquals("Michelso: mean", mean, u.getMean(), 1E-13); + loadStats("data/NumAcc1.txt", u); assertEquals("NumAcc1: std", std, u.getStandardDeviation(), 1E-14); assertEquals("NumAcc1: mean", mean, u.getMean(), 1E-14); - + loadStats("data/NumAcc2.txt", u); assertEquals("NumAcc2: std", std, u.getStandardDeviation(), 1E-14); assertEquals("NumAcc2: mean", mean, u.getMean(), 1E-14); @@ -87,23 +87,23 @@ public class CertifiedDataTest extends TestCase { public void testDescriptiveStatistics() throws Exception { DescriptiveStatistics u = new DescriptiveStatistics(); - + loadStats("data/PiDigits.txt", u); assertEquals("PiDigits: std", std, u.getStandardDeviation(), 1E-14); assertEquals("PiDigits: mean", mean, u.getMean(), 1E-14); - + loadStats("data/Mavro.txt", u); assertEquals("Mavro: std", std, u.getStandardDeviation(), 1E-14); - assertEquals("Mavro: mean", mean, u.getMean(), 1E-14); - + assertEquals("Mavro: mean", mean, u.getMean(), 1E-14); + loadStats("data/Michelso.txt", u); assertEquals("Michelso: std", std, u.getStandardDeviation(), 1E-14); - assertEquals("Michelso: mean", mean, u.getMean(), 1E-14); + assertEquals("Michelso: mean", mean, u.getMean(), 1E-14); loadStats("data/NumAcc1.txt", u); assertEquals("NumAcc1: std", std, u.getStandardDeviation(), 1E-14); assertEquals("NumAcc1: mean", mean, u.getMean(), 1E-14); - + loadStats("data/NumAcc2.txt", u); assertEquals("NumAcc2: std", std, u.getStandardDeviation(), 1E-14); assertEquals("NumAcc2: mean", mean, u.getMean(), 1E-14); @@ -115,7 +115,7 @@ public class CertifiedDataTest extends TestCase { * @param statistical summary */ private void loadStats(String resource, Object u) throws Exception { - + DescriptiveStatistics d = null; SummaryStatistics s = null; if (u instanceof DescriptiveStatistics) { @@ -127,14 +127,14 @@ public class CertifiedDataTest extends TestCase { "clear", new Class[]{}).invoke(u, new Object[]{}); mean = Double.NaN; std = Double.NaN; - + BufferedReader in = new BufferedReader( new InputStreamReader( CertifiedDataTest.class.getResourceAsStream(resource))); - + String line = null; - + for (int j = 0; j < 60; j++) { line = in.readLine(); if (j == 40) { @@ -148,9 +148,9 @@ public class CertifiedDataTest extends TestCase { line.substring(line.lastIndexOf(":") + 1).trim()); } } - + line = in.readLine(); - + while (line != null) { if (d != null) { d.addValue(Double.parseDouble(line.trim())); @@ -159,7 +159,7 @@ public class CertifiedDataTest extends TestCase { } line = in.readLine(); } - + in.close(); } } diff --git a/src/test/java/org/apache/commons/math/stat/FrequencyTest.java b/src/test/java/org/apache/commons/math/stat/FrequencyTest.java index 919f330ba..4fcbe2b5c 100644 --- a/src/test/java/org/apache/commons/math/stat/FrequencyTest.java +++ b/src/test/java/org/apache/commons/math/stat/FrequencyTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -42,22 +42,22 @@ public final class FrequencyTest extends TestCase { private int threeI=3; private double tolerance = 10E-15; private Frequency f = null; - + public FrequencyTest(String name) { super(name); } @Override - public void setUp() { + public void setUp() { f = new Frequency(); } - + public static Test suite() { TestSuite suite = new TestSuite(FrequencyTest.class); suite.setName("Frequency Tests"); return suite; } - + /** test freq counts */ public void testCounts() { assertEquals("total count",0,f.getSumFreq()); @@ -75,10 +75,10 @@ public final class FrequencyTest extends TestCase { assertEquals("Integer argument cum freq",4, f.getCumFreq(Integer.valueOf(2))); assertEquals("five cumulative frequency", 4, f.getCumFreq(5)); assertEquals("foo cumulative frequency", 0, f.getCumFreq("foo")); - + f.clear(); assertEquals("total count",0,f.getSumFreq()); - + // userguide examples ------------------------------------------------------------------- f.addValue("one"); f.addValue("One"); @@ -89,7 +89,7 @@ public final class FrequencyTest extends TestCase { assertEquals("z cumulative pct", 1.0, f.getCumPct("z"), tolerance); assertEquals("Ot cumulative pct", 0.25, f.getCumPct("Ot"), tolerance); f.clear(); - + f = null; Frequency f = new Frequency(); f.addValue(1); @@ -102,8 +102,8 @@ public final class FrequencyTest extends TestCase { assertEquals("0 cum pct", 0.2, f.getCumPct(0), tolerance); assertEquals("1 pct", 0.6, f.getPct(Integer.valueOf(1)), tolerance); assertEquals("-2 cum pct", 0, f.getCumPct(-2), tolerance); - assertEquals("10 cum pct", 1, f.getCumPct(10), tolerance); - + assertEquals("10 cum pct", 1, f.getCumPct(10), tolerance); + f = null; f = new Frequency(String.CASE_INSENSITIVE_ORDER); f.addValue("one"); @@ -129,8 +129,8 @@ public final class FrequencyTest extends TestCase { assertEquals(0.25, f.getPct('a'), 0.0); assertEquals(0.5, f.getCumPct('b'), 0.0); assertEquals(1.0, f.getCumPct('e'), 0.0); - } - + } + /** test pcts */ public void testPcts() { f.addValue(oneL); @@ -154,7 +154,7 @@ public final class FrequencyTest extends TestCase { assertEquals("zero cum pct",0.0,f.getCumPct(0),tolerance); assertEquals("foo cum pct",0,f.getCumPct("foo"),tolerance); } - + /** test adding incomparable values */ public void testAdd() { char aChar = 'a'; @@ -163,7 +163,7 @@ public final class FrequencyTest extends TestCase { f.addValue(aChar); f.addValue(bChar); try { - f.addValue(aString); + f.addValue(aString); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected @@ -178,17 +178,17 @@ public final class FrequencyTest extends TestCase { assertEquals("b cum pct",1.0,f.getCumPct(bChar),tolerance); assertEquals("a string pct",0.0,f.getPct(aString),tolerance); assertEquals("a string cum pct",0.0,f.getCumPct(aString),tolerance); - + f = new Frequency(); f.addValue("One"); try { - f.addValue(new Integer("One")); + f.addValue(new Integer("One")); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } - + // Check what happens when non-Comparable objects are added @SuppressWarnings("deprecation") public void testAddNonComparable(){ @@ -216,18 +216,18 @@ public final class FrequencyTest extends TestCase { assertTrue("pct, empty table", Double.isNaN(f.getPct(0))); assertTrue("pct, empty table", Double.isNaN(f.getPct(Integer.valueOf(0)))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(0))); - assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(Integer.valueOf(0)))); + assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(Integer.valueOf(0)))); } - + /** - * Tests toString() + * Tests toString() */ public void testToString(){ f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); - + String s = f.toString(); //System.out.println(s); assertNotNull(s); @@ -235,10 +235,10 @@ public final class FrequencyTest extends TestCase { try { String line = reader.readLine(); // header line assertNotNull(line); - + line = reader.readLine(); // one's or two's line assertNotNull(line); - + line = reader.readLine(); // one's or two's line assertNotNull(line); @@ -246,7 +246,7 @@ public final class FrequencyTest extends TestCase { assertNull(line); } catch(IOException ex){ fail(ex.getMessage()); - } + } } public void testIntegerValues() { Comparable obj1 = null; @@ -265,9 +265,9 @@ public final class FrequencyTest extends TestCase { Iterator it = f.valuesIterator(); while (it.hasNext()) { assertTrue(it.next() instanceof Long); - } + } } - + public void testSerial() { f.addValue(oneL); f.addValue(twoL); diff --git a/src/test/java/org/apache/commons/math/stat/StatUtilsTest.java b/src/test/java/org/apache/commons/math/stat/StatUtilsTest.java index 12e8af08b..e30f5fc46 100644 --- a/src/test/java/org/apache/commons/math/stat/StatUtilsTest.java +++ b/src/test/java/org/apache/commons/math/stat/StatUtilsTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -117,10 +117,10 @@ public final class StatUtilsTest extends TestCase { } } - + public void testSumSq() { double[] x = null; - + // test null try { StatUtils.sumSq(x); @@ -128,33 +128,33 @@ public final class StatUtilsTest extends TestCase { } catch (IllegalArgumentException ex) { // success } - + try { StatUtils.sumSq(x, 0, 4); fail("null is not a valid data array."); } catch (IllegalArgumentException ex) { // success } - + // test empty x = new double[] {}; TestUtils.assertEquals(Double.NaN, StatUtils.sumSq(x), tolerance); TestUtils.assertEquals(Double.NaN, StatUtils.sumSq(x, 0, 0), tolerance); - + // test one x = new double[] {two}; TestUtils.assertEquals(4, StatUtils.sumSq(x), tolerance); TestUtils.assertEquals(4, StatUtils.sumSq(x, 0, 1), tolerance); - + // test many x = new double[] {one, two, two, three}; TestUtils.assertEquals(18, StatUtils.sumSq(x), tolerance); TestUtils.assertEquals(8, StatUtils.sumSq(x, 1, 2), tolerance); } - + public void testProduct() { double[] x = null; - + // test null try { StatUtils.product(x); @@ -162,33 +162,33 @@ public final class StatUtilsTest extends TestCase { } catch (IllegalArgumentException ex) { // success } - + try { StatUtils.product(x, 0, 4); fail("null is not a valid data array."); } catch (IllegalArgumentException ex) { // success } - + // test empty x = new double[] {}; TestUtils.assertEquals(Double.NaN, StatUtils.product(x), tolerance); TestUtils.assertEquals(Double.NaN, StatUtils.product(x, 0, 0), tolerance); - + // test one x = new double[] {two}; TestUtils.assertEquals(two, StatUtils.product(x), tolerance); TestUtils.assertEquals(two, StatUtils.product(x, 0, 1), tolerance); - + // test many x = new double[] {one, two, two, three}; TestUtils.assertEquals(12, StatUtils.product(x), tolerance); TestUtils.assertEquals(4, StatUtils.product(x, 1, 2), tolerance); } - + public void testSumLog() { double[] x = null; - + // test null try { StatUtils.sumLog(x); @@ -196,98 +196,98 @@ public final class StatUtilsTest extends TestCase { } catch (IllegalArgumentException ex) { // success } - + try { StatUtils.sumLog(x, 0, 4); fail("null is not a valid data array."); } catch (IllegalArgumentException ex) { // success } - + // test empty x = new double[] {}; TestUtils.assertEquals(Double.NaN, StatUtils.sumLog(x), tolerance); TestUtils.assertEquals(Double.NaN, StatUtils.sumLog(x, 0, 0), tolerance); - + // test one x = new double[] {two}; TestUtils.assertEquals(Math.log(two), StatUtils.sumLog(x), tolerance); TestUtils.assertEquals(Math.log(two), StatUtils.sumLog(x, 0, 1), tolerance); - + // test many x = new double[] {one, two, two, three}; TestUtils.assertEquals(Math.log(one) + 2.0 * Math.log(two) + Math.log(three), StatUtils.sumLog(x), tolerance); TestUtils.assertEquals(2.0 * Math.log(two), StatUtils.sumLog(x, 1, 2), tolerance); } - + public void testMean() { double[] x = null; - + try { StatUtils.mean(x, 0, 4); fail("null is not a valid data array."); } catch (IllegalArgumentException ex) { // success } - + // test empty x = new double[] {}; TestUtils.assertEquals(Double.NaN, StatUtils.mean(x, 0, 0), tolerance); - + // test one x = new double[] {two}; TestUtils.assertEquals(two, StatUtils.mean(x, 0, 1), tolerance); - + // test many x = new double[] {one, two, two, three}; TestUtils.assertEquals(2.5, StatUtils.mean(x, 2, 2), tolerance); } - + public void testVariance() { double[] x = null; - + try { StatUtils.variance(x, 0, 4); fail("null is not a valid data array."); } catch (IllegalArgumentException ex) { // success } - + // test empty x = new double[] {}; TestUtils.assertEquals(Double.NaN, StatUtils.variance(x, 0, 0), tolerance); - + // test one x = new double[] {two}; TestUtils.assertEquals(0.0, StatUtils.variance(x, 0, 1), tolerance); - + // test many x = new double[] {one, two, two, three}; TestUtils.assertEquals(0.5, StatUtils.variance(x, 2, 2), tolerance); - + // test precomputed mean x = new double[] {one, two, two, three}; TestUtils.assertEquals(0.5, StatUtils.variance(x,2.5, 2, 2), tolerance); } - + public void testMax() { double[] x = null; - + try { StatUtils.max(x, 0, 4); fail("null is not a valid data array."); } catch (IllegalArgumentException ex) { // success } - + // test empty x = new double[] {}; TestUtils.assertEquals(Double.NaN, StatUtils.max(x, 0, 0), tolerance); - + // test one x = new double[] {two}; TestUtils.assertEquals(two, StatUtils.max(x, 0, 1), tolerance); - + // test many x = new double[] {one, two, two, three}; TestUtils.assertEquals(three, StatUtils.max(x, 1, 3), tolerance); @@ -299,7 +299,7 @@ public final class StatUtilsTest extends TestCase { // test middle nan is ignored x = new double[] {one, nan, three}; TestUtils.assertEquals(three, StatUtils.max(x), tolerance); - + // test last nan is ignored x = new double[] {one, two, nan}; TestUtils.assertEquals(two, StatUtils.max(x), tolerance); @@ -308,25 +308,25 @@ public final class StatUtilsTest extends TestCase { x = new double[] {nan, nan, nan}; TestUtils.assertEquals(nan, StatUtils.max(x), tolerance); } - + public void testMin() { double[] x = null; - + try { StatUtils.min(x, 0, 4); fail("null is not a valid data array."); } catch (IllegalArgumentException ex) { // success } - + // test empty x = new double[] {}; TestUtils.assertEquals(Double.NaN, StatUtils.min(x, 0, 0), tolerance); - + // test one x = new double[] {two}; TestUtils.assertEquals(two, StatUtils.min(x, 0, 1), tolerance); - + // test many x = new double[] {one, two, two, three}; TestUtils.assertEquals(two, StatUtils.min(x, 1, 3), tolerance); @@ -338,7 +338,7 @@ public final class StatUtilsTest extends TestCase { // test middle nan is ignored x = new double[] {one, nan, three}; TestUtils.assertEquals(one, StatUtils.min(x), tolerance); - + // test last nan is ignored x = new double[] {one, two, nan}; TestUtils.assertEquals(one, StatUtils.min(x), tolerance); @@ -347,10 +347,10 @@ public final class StatUtilsTest extends TestCase { x = new double[] {nan, nan, nan}; TestUtils.assertEquals(nan, StatUtils.min(x), tolerance); } - + public void testPercentile() { double[] x = null; - + // test null try { StatUtils.percentile(x, .25); @@ -358,30 +358,30 @@ public final class StatUtilsTest extends TestCase { } catch (IllegalArgumentException ex) { // success } - + try { StatUtils.percentile(x, 0, 4, 0.25); fail("null is not a valid data array."); } catch (IllegalArgumentException ex) { // success } - + // test empty x = new double[] {}; TestUtils.assertEquals(Double.NaN, StatUtils.percentile(x, 25), tolerance); TestUtils.assertEquals(Double.NaN, StatUtils.percentile(x, 0, 0, 25), tolerance); - + // test one x = new double[] {two}; TestUtils.assertEquals(two, StatUtils.percentile(x, 25), tolerance); TestUtils.assertEquals(two, StatUtils.percentile(x, 0, 1, 25), tolerance); - + // test many x = new double[] {one, two, two, three}; TestUtils.assertEquals(2.5, StatUtils.percentile(x, 70), tolerance); TestUtils.assertEquals(2.5, StatUtils.percentile(x, 1, 3, 62.5), tolerance); } - + public void testDifferenceStats() throws Exception { double sample1[] = {1d, 2d, 3d, 4d}; double sample2[] = {1d, 3d, 4d, 2d}; @@ -390,7 +390,7 @@ public final class StatUtilsTest extends TestCase { double meanDifference = StatUtils.meanDifference(sample1, sample2); assertEquals(StatUtils.sumDifference(sample1, sample2), StatUtils.sum(diff), tolerance); assertEquals(meanDifference, StatUtils.mean(diff), tolerance); - assertEquals(StatUtils.varianceDifference(sample1, sample2, meanDifference), + assertEquals(StatUtils.varianceDifference(sample1, sample2, meanDifference), StatUtils.variance(diff), tolerance); try { StatUtils.meanDifference(sample1, small); @@ -412,7 +412,7 @@ public final class StatUtilsTest extends TestCase { // expected } } - + public void testGeometricMean() throws Exception { double[] test = null; try { @@ -422,9 +422,9 @@ public final class StatUtilsTest extends TestCase { // expected } test = new double[] {2, 4, 6, 8}; - assertEquals(Math.exp(0.25d * StatUtils.sumLog(test)), + assertEquals(Math.exp(0.25d * StatUtils.sumLog(test)), StatUtils.geometricMean(test), Double.MIN_VALUE); - assertEquals(Math.exp(0.5 * StatUtils.sumLog(test, 0, 2)), + assertEquals(Math.exp(0.5 * StatUtils.sumLog(test, 0, 2)), StatUtils.geometricMean(test, 0, 2), Double.MIN_VALUE); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/math/stat/clustering/EuclideanIntegerPointTest.java b/src/test/java/org/apache/commons/math/stat/clustering/EuclideanIntegerPointTest.java index 2f760ddc1..572ce50f1 100644 --- a/src/test/java/org/apache/commons/math/stat/clustering/EuclideanIntegerPointTest.java +++ b/src/test/java/org/apache/commons/math/stat/clustering/EuclideanIntegerPointTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,7 +33,7 @@ public class EuclideanIntegerPointTest { int[] array = { -3, -2, -1, 0, 1 }; assertTrue(array == new EuclideanIntegerPoint(array).getPoint()); } - + @Test public void testDistance() { EuclideanIntegerPoint e1 = new EuclideanIntegerPoint(new int[] { -3, -2, -1, 0, 1 }); @@ -42,7 +42,7 @@ public class EuclideanIntegerPointTest { assertEquals(0.0, e1.distanceFrom(e1), 1.0e-15); assertEquals(0.0, e2.distanceFrom(e2), 1.0e-15); } - + @Test public void testCentroid() { List list = new ArrayList(); @@ -54,11 +54,11 @@ public class EuclideanIntegerPointTest { assertEquals(2, c.getPoint()[0]); assertEquals(3, c.getPoint()[1]); } - + @Test public void testSerial() { EuclideanIntegerPoint p = new EuclideanIntegerPoint(new int[] { -3, -2, -1, 0, 1 }); assertEquals(p, TestUtils.serializeAndRecover(p)); } - + } diff --git a/src/test/java/org/apache/commons/math/stat/correlation/CovarianceTest.java b/src/test/java/org/apache/commons/math/stat/correlation/CovarianceTest.java index 67250b697..b603bb937 100644 --- a/src/test/java/org/apache/commons/math/stat/correlation/CovarianceTest.java +++ b/src/test/java/org/apache/commons/math/stat/correlation/CovarianceTest.java @@ -24,7 +24,7 @@ import org.apache.commons.math.stat.descriptive.moment.Variance; import junit.framework.TestCase; public class CovarianceTest extends TestCase { - + protected final double[] longleyData = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, @@ -43,7 +43,7 @@ public class CovarianceTest extends TestCase { 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; - + protected final double[] swissData = new double[] { 80.2,17.0,15,12,9.96, 83.1,45.1,6,9,84.84, @@ -93,19 +93,19 @@ public class CovarianceTest extends TestCase { 44.7,46.6,16,29,50.43, 42.8,27.7,22,29,58.33 }; - - + + /** * Test Longley dataset against R. * Data Source: J. Longley (1967) "An Appraisal of Least Squares * Programs for the Electronic Computer from the Point of View of the User" * Journal of the American Statistical Association, vol. 62. September, * pp. 819-841. - * + * * Data are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */ - public void testLongly() { + public void testLongly() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); RealMatrix covarianceMatrix = new Covariance(matrix).getCovarianceMatrix(); double[] rData = new double[] { @@ -124,11 +124,11 @@ public class CovarianceTest extends TestCase { 16240.93333333333, 5.092333333333334e+01, 470977.900000000, 2973.033333333333, 1382.433333333333, 32917.40000000, 22.66666666666667 }; - + TestUtils.assertEquals("covariance matrix", createRealMatrix(rData, 7, 7), covarianceMatrix, 10E-9); } - + /** * Test R Swiss fertility dataset against R. * Data Source: R datasets package @@ -143,10 +143,10 @@ public class CovarianceTest extends TestCase { -79.7295097132285, -139.6574005550416, 53.57585568917669, 92.4560592044403, -61.6988297872340, 241.5632030527289, 379.9043755781684, -190.56061054579092, -61.6988297872340, 1739.2945371877890 }; - + TestUtils.assertEquals("covariance matrix", createRealMatrix(rData, 5, 5), covarianceMatrix, 10E-13); } - + /** * Constant column */ @@ -156,8 +156,8 @@ public class CovarianceTest extends TestCase { assertEquals(0d, new Covariance().covariance(noVariance, values, true), Double.MIN_VALUE); assertEquals(0d, new Covariance().covariance(noVariance, noVariance, true), Double.MIN_VALUE); } - - + + /** * Insufficient data */ @@ -178,7 +178,7 @@ public class CovarianceTest extends TestCase { // Expected } } - + /** * Verify that diagonal entries are consistent with Variance computation and matrix matches * column-by-column covariances @@ -186,18 +186,18 @@ public class CovarianceTest extends TestCase { public void testConsistency() { final RealMatrix matrix = createRealMatrix(swissData, 47, 5); final RealMatrix covarianceMatrix = new Covariance(matrix).getCovarianceMatrix(); - + // Variances on the diagonal Variance variance = new Variance(); for (int i = 0; i < 5; i++) { assertEquals(variance.evaluate(matrix.getColumn(i)), covarianceMatrix.getEntry(i,i), 10E-14); } - + // Symmetry, column-consistency - assertEquals(covarianceMatrix.getEntry(2, 3), + assertEquals(covarianceMatrix.getEntry(2, 3), new Covariance().covariance(matrix.getColumn(2), matrix.getColumn(3), true), 10E-14); assertEquals(covarianceMatrix.getEntry(2, 3), covarianceMatrix.getEntry(3, 2), Double.MIN_VALUE); - + // All columns same -> all entries = column variance RealMatrix repeatedColumns = new Array2DRowRealMatrix(47, 3); for (int i = 0; i < 3; i++) { @@ -210,20 +210,20 @@ public class CovarianceTest extends TestCase { assertEquals(columnVariance, repeatedCovarianceMatrix.getEntry(i, j), 10E-14); } } - + // Check bias-correction defaults double[][] data = matrix.getData(); - TestUtils.assertEquals("Covariances", + TestUtils.assertEquals("Covariances", covarianceMatrix, new Covariance().computeCovarianceMatrix(data),Double.MIN_VALUE); - TestUtils.assertEquals("Covariances", + TestUtils.assertEquals("Covariances", covarianceMatrix, new Covariance().computeCovarianceMatrix(data, true),Double.MIN_VALUE); - + double[] x = data[0]; double[] y = data[1]; - assertEquals(new Covariance().covariance(x, y), - new Covariance().covariance(x, y, true), Double.MIN_VALUE); + assertEquals(new Covariance().covariance(x, y), + new Covariance().covariance(x, y, true), Double.MIN_VALUE); } - + protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols) { double[][] matrixData = new double[nRows][nCols]; int ptr = 0; @@ -231,6 +231,6 @@ public class CovarianceTest extends TestCase { System.arraycopy(data, ptr, matrixData[i], 0, nCols); ptr += nCols; } - return new Array2DRowRealMatrix(matrixData); + return new Array2DRowRealMatrix(matrixData); } } diff --git a/src/test/java/org/apache/commons/math/stat/correlation/PearsonsCorrelationTest.java b/src/test/java/org/apache/commons/math/stat/correlation/PearsonsCorrelationTest.java index 74c2d7fbb..28a7b8e08 100644 --- a/src/test/java/org/apache/commons/math/stat/correlation/PearsonsCorrelationTest.java +++ b/src/test/java/org/apache/commons/math/stat/correlation/PearsonsCorrelationTest.java @@ -25,7 +25,7 @@ import org.apache.commons.math.linear.BlockRealMatrix; import junit.framework.TestCase; public class PearsonsCorrelationTest extends TestCase { - + protected final double[] longleyData = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, @@ -44,7 +44,7 @@ public class PearsonsCorrelationTest extends TestCase { 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; - + protected final double[] swissData = new double[] { 80.2,17.0,15,12,9.96, 83.1,45.1,6,9,84.84, @@ -94,14 +94,14 @@ public class PearsonsCorrelationTest extends TestCase { 44.7,46.6,16,29,50.43, 42.8,27.7,22,29,58.33 }; - - + + /** * Test Longley dataset against R. */ - public void testLongly() throws Exception { + public void testLongly() throws Exception { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); - PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); + PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1.000000000000000, 0.9708985250610560, 0.9835516111796693, 0.5024980838759942, @@ -118,28 +118,28 @@ public class PearsonsCorrelationTest extends TestCase { 0.3644162671890320, 1.000000000000000, 0.9939528462329257, 0.971329459192119, 0.9911491900672053, 0.9952734837647849, 0.6682566045621746, 0.4172451498349454, 0.993952846232926, 1.0000000000000000 - }; + }; TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 7, 7), correlationMatrix, 10E-15); - + double[] rPvalues = new double[] { 4.38904690369668e-10, 8.36353208910623e-12, 7.8159700933611e-14, - 0.0472894097790304, 0.01030636128354301, 0.01316878049026582, + 0.0472894097790304, 0.01030636128354301, 0.01316878049026582, 0.0749178049642416, 0.06971758330341182, 0.0830166169296545, 0.510948586323452, - 3.693245043123738e-09, 4.327782576751815e-11, 1.167954621905665e-13, 0.00331028281967516, 0.1652293725106684, + 3.693245043123738e-09, 4.327782576751815e-11, 1.167954621905665e-13, 0.00331028281967516, 0.1652293725106684, 3.95834476307755e-10, 1.114663916723657e-13, 1.332267629550188e-15, 0.00466039138541463, 0.1078477071581498, 7.771561172376096e-15 }; RealMatrix rPMatrix = createLowerTriangularRealMatrix(rPvalues, 7); fillUpper(rPMatrix, 0d); TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15); } - + /** * Test R Swiss fertility dataset against R. */ public void testSwissFertility() throws Exception { RealMatrix matrix = createRealMatrix(swissData, 47, 5); - PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); + PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1.0000000000000000, 0.3530791836199747, -0.6458827064572875, -0.6637888570350691, 0.4636847006517939, @@ -149,7 +149,7 @@ public class PearsonsCorrelationTest extends TestCase { 0.4636847006517939, 0.4010950530487398, -0.5727418060641666, -0.1538589170909148, 1.0000000000000000 }; TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 5, 5), correlationMatrix, 10E-15); - + double[] rPvalues = new double[] { 0.01491720061472623, 9.45043734069043e-07, 9.95151527133974e-08, @@ -160,7 +160,7 @@ public class PearsonsCorrelationTest extends TestCase { fillUpper(rPMatrix, 0d); TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15); } - + /** * Constant column */ @@ -169,12 +169,12 @@ public class PearsonsCorrelationTest extends TestCase { double[] values = new double[] {1, 2, 3, 4}; assertTrue(Double.isNaN(new PearsonsCorrelation().correlation(noVariance, values))); } - - + + /** * Insufficient data */ - + public void testInsufficientData() { double[] one = new double[] {1}; double[] two = new double[] {2}; @@ -192,7 +192,7 @@ public class PearsonsCorrelationTest extends TestCase { // Expected } } - + /** * Verify that direct t-tests using standard error estimates are consistent * with reported p-values @@ -200,7 +200,7 @@ public class PearsonsCorrelationTest extends TestCase { public void testStdErrorConsistency() throws Exception { TDistribution tDistribution = new TDistributionImpl(45); RealMatrix matrix = createRealMatrix(swissData, 47, 5); - PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); + PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix rValues = corrInstance.getCorrelationMatrix(); RealMatrix pValues = corrInstance.getCorrelationPValues(); RealMatrix stdErrors = corrInstance.getCorrelationStandardErrors(); @@ -212,14 +212,14 @@ public class PearsonsCorrelationTest extends TestCase { } } } - + /** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */ public void testCovarianceConsistency() throws Exception { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); - PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); + PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); Covariance covInstance = new Covariance(matrix); PearsonsCorrelation corrFromCovInstance = new PearsonsCorrelation(covInstance); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), @@ -228,8 +228,8 @@ public class PearsonsCorrelationTest extends TestCase { corrFromCovInstance.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance.getCorrelationStandardErrors(), 10E-15); - - PearsonsCorrelation corrFromCovInstance2 = + + PearsonsCorrelation corrFromCovInstance2 = new PearsonsCorrelation(covInstance.getCovarianceMatrix(), 16); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance2.getCorrelationMatrix(), 10E-15); @@ -238,20 +238,20 @@ public class PearsonsCorrelationTest extends TestCase { TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance2.getCorrelationStandardErrors(), 10E-15); } - - + + public void testConsistency() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); - PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); + PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); double[][] data = matrix.getData(); double[] x = matrix.getColumn(0); double[] y = matrix.getColumn(1); - assertEquals(new PearsonsCorrelation().correlation(x, y), + assertEquals(new PearsonsCorrelation().correlation(x, y), corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE); TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(), new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE); } - + protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols) { double[][] matrixData = new double[nRows][nCols]; int ptr = 0; @@ -259,9 +259,9 @@ public class PearsonsCorrelationTest extends TestCase { System.arraycopy(data, ptr, matrixData[i], 0, nCols); ptr += nCols; } - return new BlockRealMatrix(matrixData); + return new BlockRealMatrix(matrixData); } - + protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension) { int ptr = 0; RealMatrix result = new BlockRealMatrix(dimension, dimension); @@ -273,7 +273,7 @@ public class PearsonsCorrelationTest extends TestCase { } return result; } - + protected void fillUpper(RealMatrix matrix, double diagonalValue) { int dimension = matrix.getColumnDimension(); for (int i = 0; i < dimension; i++) { @@ -281,6 +281,6 @@ public class PearsonsCorrelationTest extends TestCase { for (int j = i+1; j < dimension; j++) { matrix.setEntry(i, j, matrix.getEntry(j, i)); } - } + } } } diff --git a/src/test/java/org/apache/commons/math/stat/correlation/SpearmansRankCorrelationTest.java b/src/test/java/org/apache/commons/math/stat/correlation/SpearmansRankCorrelationTest.java index 2e83c55a2..33438a99b 100644 --- a/src/test/java/org/apache/commons/math/stat/correlation/SpearmansRankCorrelationTest.java +++ b/src/test/java/org/apache/commons/math/stat/correlation/SpearmansRankCorrelationTest.java @@ -22,7 +22,7 @@ import org.apache.commons.math.linear.RealMatrix; /** * Test cases for Spearman's rank correlation - * + * * @since 2.0 * @version $Revision$ $Date$ */ @@ -37,14 +37,14 @@ public class SpearmansRankCorrelationTest extends PearsonsCorrelationTest { protected void tearDown() throws Exception { super.tearDown(); } - + /** * Test Longley dataset against R. */ @Override - public void testLongly() throws Exception { + public void testLongly() throws Exception { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); - SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix); + SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1, 0.982352941176471, 0.985294117647059, 0.564705882352941, 0.2264705882352941, 0.976470588235294, @@ -55,16 +55,16 @@ public class SpearmansRankCorrelationTest extends PearsonsCorrelationTest { 0.2205882352941176, 0.2235294117647059, -0.3411764705882353, 1, 0.2264705882352941, 0.2264705882352941, 0.976470588235294, 0.997058823529412, 0.9941176470588236, 0.685294117647059, 0.2264705882352941, 1, 1, 0.976470588235294, 0.997058823529412, 0.9941176470588236, 0.685294117647059, 0.2264705882352941, 1, 1 - }; + }; TestUtils.assertEquals("Spearman's correlation matrix", createRealMatrix(rData, 7, 7), correlationMatrix, 10E-15); } - + /** * Test R swiss fertility dataset. */ - public void testSwiss() throws Exception { + public void testSwiss() throws Exception { RealMatrix matrix = createRealMatrix(swissData, 47, 5); - SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix); + SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1, 0.2426642769364176, -0.660902996352354, -0.443257690360988, 0.4136455623012432, @@ -72,10 +72,10 @@ public class SpearmansRankCorrelationTest extends PearsonsCorrelationTest { -0.660902996352354, -0.598859938748963, 1, 0.674603831406147, -0.4750575257171745, -0.443257690360988, -0.650463814145816, 0.674603831406147, 1, -0.1444163088302244, 0.4136455623012432, 0.2886878090882852, -0.4750575257171745, -0.1444163088302244, 1 - }; + }; TestUtils.assertEquals("Spearman's correlation matrix", createRealMatrix(rData, 5, 5), correlationMatrix, 10E-15); } - + /** * Constant column */ @@ -85,10 +85,10 @@ public class SpearmansRankCorrelationTest extends PearsonsCorrelationTest { double[] values = new double[] {1, 2, 3, 4}; assertTrue(Double.isNaN(new SpearmansCorrelation().correlation(noVariance, values))); } - + /** * Insufficient data - */ + */ @Override public void testInsufficientData() { double[] one = new double[] {1}; @@ -107,24 +107,24 @@ public class SpearmansRankCorrelationTest extends PearsonsCorrelationTest { // Expected } } - + @Override public void testConsistency() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); - SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix); + SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix); double[][] data = matrix.getData(); double[] x = matrix.getColumn(0); double[] y = matrix.getColumn(1); - assertEquals(new SpearmansCorrelation().correlation(x, y), + assertEquals(new SpearmansCorrelation().correlation(x, y), corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE); TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(), new SpearmansCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE); } - + // Not relevant here @Override public void testStdErrorConsistency() throws Exception {} @Override public void testCovarianceConsistency() throws Exception {} - + } diff --git a/src/test/java/org/apache/commons/math/stat/data/CertifiedDataAbstractTest.java b/src/test/java/org/apache/commons/math/stat/data/CertifiedDataAbstractTest.java index 5cf8f98ed..21a878d63 100644 --- a/src/test/java/org/apache/commons/math/stat/data/CertifiedDataAbstractTest.java +++ b/src/test/java/org/apache/commons/math/stat/data/CertifiedDataAbstractTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -36,11 +36,11 @@ import org.apache.commons.math.stat.descriptive.SummaryStatistics; * @version $Revision$ $Date$ */ public abstract class CertifiedDataAbstractTest extends TestCase { - + private DescriptiveStatistics descriptives; - + private SummaryStatistics summaries; - + private Map certifiedValues; @Override @@ -48,7 +48,7 @@ public abstract class CertifiedDataAbstractTest extends TestCase { descriptives = new DescriptiveStatistics(); summaries = new SummaryStatistics(); certifiedValues = new HashMap(); - + loadData(); } @@ -58,12 +58,12 @@ public abstract class CertifiedDataAbstractTest extends TestCase { try { URL resourceURL = getClass().getClassLoader().getResource(getResourceName()); in = new BufferedReader(new InputStreamReader(resourceURL.openStream())); - + String line = in.readLine(); while (line != null) { - - /* this call to StringUtils did little for the - * following conditional structure + + /* this call to StringUtils did little for the + * following conditional structure */ line = line.trim(); @@ -102,14 +102,14 @@ public abstract class CertifiedDataAbstractTest extends TestCase { protected void tearDown() throws Exception { descriptives.clear(); descriptives = null; - + summaries.clear(); summaries = null; - + certifiedValues.clear(); certifiedValues = null; } - + public void testCertifiedValues() { for (String name : certifiedValues.keySet()) { Double expectedValue = certifiedValues.get(name); @@ -129,12 +129,12 @@ public abstract class CertifiedDataAbstractTest extends TestCase { } } } - - + + protected Double getProperty(Object bean, String name) { try { // Get the value of prop - String prop = "get" + name.substring(0,1).toUpperCase() + name.substring(1); + String prop = "get" + name.substring(0,1).toUpperCase() + name.substring(1); Method meth = bean.getClass().getMethod(prop, new Class[0]); Object property = meth.invoke(bean, new Object[0]); if (meth.getReturnType().equals(Double.TYPE)) { diff --git a/src/test/java/org/apache/commons/math/stat/data/LewTest.java b/src/test/java/org/apache/commons/math/stat/data/LewTest.java index d7f58b5d9..dfddf7804 100644 --- a/src/test/java/org/apache/commons/math/stat/data/LewTest.java +++ b/src/test/java/org/apache/commons/math/stat/data/LewTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/test/java/org/apache/commons/math/stat/data/LotteryTest.java b/src/test/java/org/apache/commons/math/stat/data/LotteryTest.java index 1233de1bd..c6f4db92d 100644 --- a/src/test/java/org/apache/commons/math/stat/data/LotteryTest.java +++ b/src/test/java/org/apache/commons/math/stat/data/LotteryTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/AbstractUnivariateStatisticTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/AbstractUnivariateStatisticTest.java index 1767275d4..69cea7521 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/AbstractUnivariateStatisticTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/AbstractUnivariateStatisticTest.java @@ -23,38 +23,38 @@ import junit.framework.TestSuite; import org.apache.commons.math.stat.descriptive.moment.Mean; /** - * Tests for AbstractUnivariateStatistic + * Tests for AbstractUnivariateStatistic * * @version $Revision$ $Date$ */ public class AbstractUnivariateStatisticTest extends TestCase { - + public AbstractUnivariateStatisticTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(AbstractUnivariateStatisticTest.class); suite.setName("AbstractUnivariateStatistic Tests"); return suite; } - + protected double[] testArray = {0, 1, 2, 3, 4, 5}; protected double[] testWeightsArray = {0.3, 0.2, 1.3, 1.1, 1.0, 1.8}; protected double[] testNegativeWeightsArray = {-0.3, 0.2, -1.3, 1.1, 1.0, 1.8}; protected double[] nullArray = null; protected double[] singletonArray = {0}; protected Mean testStatistic = new Mean(); - + public void testTestPositive() { for (int j = 0; j < 6; j++) { for (int i = 1; i < (7 - j); i++) { assertTrue(testStatistic.test(testArray, 0, i)); - } + } } assertTrue(testStatistic.test(singletonArray, 0, 1)); } - + public void testTestNegative() { assertFalse(testStatistic.test(singletonArray, 0, 0)); assertFalse(testStatistic.test(testArray, 0, 0)); diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/AggregateSummaryStatisticsTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/AggregateSummaryStatisticsTest.java index 77cacfe3c..15c92fdb4 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/AggregateSummaryStatisticsTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/AggregateSummaryStatisticsTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -34,7 +34,7 @@ import org.apache.commons.math.TestUtils; * */ public class AggregateSummaryStatisticsTest extends TestCase { - + /** * Creates and returns a {@code Test} representing all the test cases in this * class @@ -46,7 +46,7 @@ public class AggregateSummaryStatisticsTest extends TestCase { suite.setName("AggregateSummaryStatistics tests"); return suite; } - + /** * Tests the standard aggregation behavior */ @@ -54,11 +54,11 @@ public class AggregateSummaryStatisticsTest extends TestCase { AggregateSummaryStatistics aggregate = new AggregateSummaryStatistics(); SummaryStatistics setOneStats = aggregate.createContributingStatistics(); SummaryStatistics setTwoStats = aggregate.createContributingStatistics(); - + assertNotNull("The set one contributing stats are null", setOneStats); assertNotNull("The set two contributing stats are null", setTwoStats); assertNotSame("Contributing stats objects are the same", setOneStats, setTwoStats); - + setOneStats.addValue(2); setOneStats.addValue(3); setOneStats.addValue(5); @@ -66,93 +66,93 @@ public class AggregateSummaryStatisticsTest extends TestCase { setOneStats.addValue(11); assertEquals("Wrong number of set one values", 5, setOneStats.getN()); assertEquals("Wrong sum of set one values", 28.0, setOneStats.getSum()); - + setTwoStats.addValue(2); setTwoStats.addValue(4); setTwoStats.addValue(8); assertEquals("Wrong number of set two values", 3, setTwoStats.getN()); assertEquals("Wrong sum of set two values", 14.0, setTwoStats.getSum()); - + assertEquals("Wrong number of aggregate values", 8, aggregate.getN()); assertEquals("Wrong aggregate sum", 42.0, aggregate.getSum()); } - + /** * Verify that aggregating over a partition gives the same results * as direct computation. - * + * * 1) Randomly generate a dataset of 10-100 values * from [-100, 100] * 2) Divide the dataset it into 2-5 partitions * 3) Create an AggregateSummaryStatistic and ContributingStatistics - * for each partition + * for each partition * 4) Compare results from the AggregateSummaryStatistic with values - * returned by a single SummaryStatistics instance that is provided + * returned by a single SummaryStatistics instance that is provided * the full dataset */ public void testAggregationConsistency() throws Exception { - + // Generate a random sample and random partition double[] totalSample = generateSample(); double[][] subSamples = generatePartition(totalSample); int nSamples = subSamples.length; - + // Create aggregator and total stats for comparison AggregateSummaryStatistics aggregate = new AggregateSummaryStatistics(); SummaryStatistics totalStats = new SummaryStatistics(); - + // Create array of component stats SummaryStatistics componentStats[] = new SummaryStatistics[nSamples]; - + for (int i = 0; i < nSamples; i++) { - + // Make componentStats[i] a contributing statistic to aggregate componentStats[i] = aggregate.createContributingStatistics(); - + // Add values from subsample for (int j = 0; j < subSamples[i].length; j++) { componentStats[i].addValue(subSamples[i][j]); } } - + // Compute totalStats directly for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } - + /* * Compare statistics in totalStats with aggregate. * Note that guaranteed success of this comparison depends on the * fact that gets values in exactly the same order - * as . - * + * as . + * */ - assertEquals(totalStats.getSummary(), aggregate.getSummary()); - + assertEquals(totalStats.getSummary(), aggregate.getSummary()); + } - + /** * Test aggregate function by randomly generating a dataset of 10-100 values * from [-100, 100], dividing it into 2-5 partitions, computing stats for each * partition and comparing the result of aggregate(...) applied to the collection * of per-partition SummaryStatistics with a single SummaryStatistics computed * over the full sample. - * + * * @throws Exception */ public void testAggregate() throws Exception { - + // Generate a random sample and random partition double[] totalSample = generateSample(); double[][] subSamples = generatePartition(totalSample); int nSamples = subSamples.length; - + // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } - + // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[nSamples]; for (int i = 0; i < nSamples; i++) { @@ -160,28 +160,28 @@ public class AggregateSummaryStatisticsTest extends TestCase { } Collection aggregate = new ArrayList(); for (int i = 0; i < nSamples; i++) { - for (int j = 0; j < subSamples[i].length; j++) { + for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } - + // Compare values StatisticalSummary aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); } - - + + public void testAggregateDegenerate() throws Exception { double[] totalSample = {1, 2, 3, 4, 5}; double[][] subSamples = {{1}, {2}, {3}, {4}, {5}}; - + // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } - + // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[5]; for (int i = 0; i < 5; i++) { @@ -189,27 +189,27 @@ public class AggregateSummaryStatisticsTest extends TestCase { } Collection aggregate = new ArrayList(); for (int i = 0; i < 5; i++) { - for (int j = 0; j < subSamples[i].length; j++) { + for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } - + // Compare values StatisticalSummaryValues aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); } - + public void testAggregateSpecialValues() throws Exception { double[] totalSample = {Double.POSITIVE_INFINITY, 2, 3, Double.NaN, 5}; double[][] subSamples = {{Double.POSITIVE_INFINITY, 2}, {3}, {Double.NaN}, {5}}; - + // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } - + // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[5]; for (int i = 0; i < 4; i++) { @@ -217,18 +217,18 @@ public class AggregateSummaryStatisticsTest extends TestCase { } Collection aggregate = new ArrayList(); for (int i = 0; i < 4; i++) { - for (int j = 0; j < subSamples[i].length; j++) { + for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } - + // Compare values StatisticalSummaryValues aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); - + } - + /** * Verifies that a StatisticalSummary and a StatisticalSummaryValues are equal up * to delta, with NaNs, infinities returned in the same spots. For max, min, n, values @@ -244,12 +244,12 @@ public class AggregateSummaryStatisticsTest extends TestCase { TestUtils.assertEquals(expected.getVariance(), observed.getVariance(), delta); } - + /** * Generates a random sample of double values. - * Sample size is random, between 10 and 100 and values are + * Sample size is random, between 10 and 100 and values are * uniformly distributed over [-100, 100]. - * + * * @return array of random double values */ private double[] generateSample() { @@ -259,13 +259,13 @@ public class AggregateSummaryStatisticsTest extends TestCase { for (int i = 0; i < out.length; i++) { out[i] = randomData.nextUniform(-100, 100); } - return out; + return out; } - + /** * Generates a partition of into up to 5 sequentially selected * subsamples with randomly selected partition points. - * + * * @param sample array to partition * @return rectangular array with rows = subsamples */ @@ -300,5 +300,5 @@ public class AggregateSummaryStatisticsTest extends TestCase { return out; } } - + } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/DescriptiveStatisticsTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/DescriptiveStatisticsTest.java index 82f3769ae..7eeac3122 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/DescriptiveStatisticsTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/DescriptiveStatisticsTest.java @@ -24,7 +24,7 @@ import org.apache.commons.math.util.MathUtils; /** * Test cases for the DescriptiveStatistics class. - * + * * @version $Revision$ $Date: 2007-08-16 15:36:33 -0500 (Thu, 16 Aug * 2007) $ */ @@ -53,7 +53,7 @@ public class DescriptiveStatisticsTest extends TestCase { stats.setMeanImpl(new deepMean()); assertEquals(42, stats.getMean(), 1E-10); } - + public void testCopy() { DescriptiveStatistics stats = createDescriptiveStatistics(); stats.addValue(1); @@ -65,7 +65,7 @@ public class DescriptiveStatisticsTest extends TestCase { copy = stats.copy(); assertEquals(42, copy.getMean(), 1E-10); } - + public void testWindowSize() { DescriptiveStatistics stats = createDescriptiveStatistics(); stats.setWindowSize(300); @@ -89,7 +89,7 @@ public class DescriptiveStatisticsTest extends TestCase { int refSum2 = refSum - (50 * 51) / 2; assertEquals(refSum2 / 50.0, stats.getMean(), 1E-10); } - + public void testGetValues() { DescriptiveStatistics stats = createDescriptiveStatistics(); for (int i = 100; i > 0; --i) { @@ -107,7 +107,7 @@ public class DescriptiveStatisticsTest extends TestCase { } assertEquals(12.0, stats.getElement(88), 1.0e-10); } - + public void testToString() { DescriptiveStatistics stats = createDescriptiveStatistics(); stats.addValue(1); @@ -161,25 +161,25 @@ public class DescriptiveStatisticsTest extends TestCase { assertEquals(reference.getGeometricMean(), shuffled.getSumsq(), 1.0e-10); } - + public void testPercentileSetter() throws Exception { DescriptiveStatistics stats = createDescriptiveStatistics(); stats.addValue(1); stats.addValue(2); stats.addValue(3); assertEquals(2, stats.getPercentile(50.0), 1E-10); - + // Inject wrapped Percentile impl stats.setPercentileImpl(new goodPercentile()); assertEquals(2, stats.getPercentile(50.0), 1E-10); - + // Try "new math" impl stats.setPercentileImpl(new subPercentile()); assertEquals(10.0, stats.getPercentile(10.0), 1E-10); - + // Try to set bad impl try { - stats.setPercentileImpl(new badPercentile()); + stats.setPercentileImpl(new badPercentile()); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected @@ -225,11 +225,11 @@ public class DescriptiveStatisticsTest extends TestCase { assertTrue(MathUtils.equals(mean3, dstat.getMean())); } - + // Test UnivariateStatistics impls for setter injection tests - + /** - * A new way to compute the mean + * A new way to compute the mean */ static class deepMean implements UnivariateStatistic { @@ -239,12 +239,12 @@ public class DescriptiveStatisticsTest extends TestCase { public double evaluate(double[] values) { return 42; - } + } public UnivariateStatistic copy() { return new deepMean(); } } - + /** * Test percentile implementation - wraps a Percentile */ @@ -258,14 +258,14 @@ public class DescriptiveStatisticsTest extends TestCase { } public double evaluate(double[] values) { return percentile.evaluate(values); - } + } public UnivariateStatistic copy() { goodPercentile result = new goodPercentile(); result.setQuantile(percentile.getQuantile()); return result; } } - + /** * Test percentile subclass - another "new math" impl * Always returns currently set quantile @@ -278,7 +278,7 @@ public class DescriptiveStatisticsTest extends TestCase { @Override public double evaluate(double[] values) { return getQuantile(); - } + } private static final long serialVersionUID = 8040701391045914979L; @Override public Percentile copy() { @@ -286,7 +286,7 @@ public class DescriptiveStatisticsTest extends TestCase { return result; } } - + /** * "Bad" test percentile implementation - no setQuantile */ @@ -302,5 +302,5 @@ public class DescriptiveStatisticsTest extends TestCase { return new badPercentile(); } } - + } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/InteractionTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/InteractionTest.java index 019af68ae..05d97e7ab 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/InteractionTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/InteractionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -67,7 +67,7 @@ public class InteractionTest extends TestCase { public void testInteraction() { - + FourthMoment m4 = new FourthMoment(); Mean m = new Mean(m4); Variance v = new Variance(m4); @@ -77,7 +77,7 @@ public class InteractionTest extends TestCase { for (int i = 0; i < testArray.length; i++){ m4.increment(testArray[i]); } - + assertEquals(mean,m.getResult(),tolerance); assertEquals(var,v.getResult(),tolerance); assertEquals(skew ,s.getResult(),tolerance); diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/ListUnivariateImpl.java b/src/test/java/org/apache/commons/math/stat/descriptive/ListUnivariateImpl.java index 842d5031d..ace001a3f 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/ListUnivariateImpl.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/ListUnivariateImpl.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,7 +33,7 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali /** Serializable version identifier */ private static final long serialVersionUID = -8837442489133392138L; - + /** * Holds a reference to a list - GENERICs are going to make * our lives easier here as we could only accept List @@ -49,7 +49,7 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali public ListUnivariateImpl(){ this(new ArrayList()); } - + /** * Construct a ListUnivariate with a specific List. * @param list The list that will back this DescriptiveStatistics @@ -57,7 +57,7 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali public ListUnivariateImpl(List list) { this(list, new DefaultTransformer()); } - + /** * Construct a ListUnivariate with a specific List. * @param list The list that will back this DescriptiveStatistics @@ -109,13 +109,13 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali calcIndex = (list.size() - windowSize) + index; } - + try { value = transformer.transform(list.get(calcIndex)); } catch (MathException e) { e.printStackTrace(); } - + return value; } @@ -141,9 +141,9 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali public void addValue(double v) { list.add(Double.valueOf(v)); } - + /** - * Adds an object to this list. + * Adds an object to this list. * @param o Object to add to the list */ public void addObject(Object o) { @@ -159,7 +159,7 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali public void clear() { list.clear(); } - + /** * Apply the given statistic to this univariate collection. * @param stat the statistic to apply @@ -174,7 +174,7 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali } return Double.NaN; } - + /** * Access the number transformer. * @return the number transformer. @@ -190,12 +190,12 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali public void setTransformer(NumberTransformer transformer) { this.transformer = transformer; } - + /** {@inheritDoc} */ @Override public synchronized void setWindowSize(int windowSize) { this.windowSize = windowSize; - //Discard elements from the front of the list if the windowSize is less than + //Discard elements from the front of the list if the windowSize is less than // the size of the list. int extra = list.size() - windowSize; for (int i = 0; i < extra; i++) { @@ -209,4 +209,4 @@ public class ListUnivariateImpl extends DescriptiveStatistics implements Seriali return windowSize; } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/ListUnivariateImplTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/ListUnivariateImplTest.java index f2f878a80..e35e070cf 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/ListUnivariateImplTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/ListUnivariateImplTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ import junit.framework.TestSuite; */ public final class ListUnivariateImplTest extends TestCase { - + private double one = 1; private float two = 2; private int three = 3; @@ -46,22 +46,22 @@ public final class ListUnivariateImplTest extends TestCase { private double min = 1; private double max = 3; private double tolerance = 10E-15; - + public ListUnivariateImplTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(ListUnivariateImplTest.class); suite.setName("Frequency Tests"); return suite; } - + /** test stats */ public void testStats() { List externalList = new ArrayList(); - - DescriptiveStatistics u = new ListUnivariateImpl( externalList ); + + DescriptiveStatistics u = new ListUnivariateImpl( externalList ); assertEquals("total count",0,u.getN(),tolerance); u.addValue(one); @@ -77,14 +77,14 @@ public final class ListUnivariateImplTest extends TestCase { assertEquals("min",min,u.getMin(),tolerance); assertEquals("max",max,u.getMax(),tolerance); u.clear(); - assertEquals("total count",0,u.getN(),tolerance); - } - + assertEquals("total count",0,u.getN(),tolerance); + } + public void testN0andN1Conditions() throws Exception { List list = new ArrayList(); - + DescriptiveStatistics u = new ListUnivariateImpl( list ); - + assertTrue("Mean of n = 0 set should be NaN", Double.isNaN( u.getMean() ) ); assertTrue("Standard Deviation of n = 0 set should be NaN", Double.isNaN( u.getStandardDeviation() ) ); assertTrue("Variance of n = 0 set should be NaN", Double.isNaN(u.getVariance() ) ); @@ -93,18 +93,18 @@ public final class ListUnivariateImplTest extends TestCase { assertTrue( "Mean of n = 1 set should be value of single item n1", u.getMean() == one); assertTrue( "StdDev of n = 1 set should be zero, instead it is: " + u.getStandardDeviation(), u.getStandardDeviation() == 0); - assertTrue( "Variance of n = 1 set should be zero", u.getVariance() == 0); + assertTrue( "Variance of n = 1 set should be zero", u.getVariance() == 0); } - + public void testSkewAndKurtosis() { DescriptiveStatistics u = new DescriptiveStatistics(); - + double[] testArray = { 12.5, 12, 11.8, 14.2, 14.9, 14.5, 21, 8.2, 10.3, 11.3, 14.1, 9.9, 12.2, 12, 12.1, 11, 19.8, 11, 10, 8.8, 9, 12.3 }; for( int i = 0; i < testArray.length; i++) { u.addValue( testArray[i]); } - + assertEquals("mean", 12.40455, u.getMean(), 0.0001); assertEquals("variance", 10.00236, u.getVariance(), 0.0001); assertEquals("skewness", 1.437424, u.getSkewness(), 0.0001); @@ -114,7 +114,7 @@ public final class ListUnivariateImplTest extends TestCase { public void testProductAndGeometricMean() throws Exception { ListUnivariateImpl u = new ListUnivariateImpl(new ArrayList()); u.setWindowSize(10); - + u.addValue( 1.0 ); u.addValue( 2.0 ); u.addValue( 3.0 ); @@ -128,26 +128,26 @@ public final class ListUnivariateImplTest extends TestCase { u.addValue( i + 2 ); } // Values should be (2,3,4,5,6,7,8,9,10,11) - + assertEquals( "Geometric mean not expected", 5.755931, u.getGeometricMean(), 0.00001 ); } - + /** test stats */ public void testSerialization() { - + DescriptiveStatistics u = new ListUnivariateImpl(); - + assertEquals("total count",0,u.getN(),tolerance); u.addValue(one); u.addValue(two); - - DescriptiveStatistics u2 = (DescriptiveStatistics)TestUtils.serializeAndRecover(u); - + + DescriptiveStatistics u2 = (DescriptiveStatistics)TestUtils.serializeAndRecover(u); + u2.addValue(two); u2.addValue(three); - + assertEquals("N",n,u2.getN(),tolerance); assertEquals("sum",sum,u2.getSum(),tolerance); assertEquals("sumsq",sumSq,u2.getSumsq(),tolerance); @@ -158,7 +158,7 @@ public final class ListUnivariateImplTest extends TestCase { assertEquals("max",max,u2.getMax(),tolerance); u2.clear(); - assertEquals("total count",0,u2.getN(),tolerance); - } + assertEquals("total count",0,u2.getN(),tolerance); + } } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/MixedListUnivariateImplTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/MixedListUnivariateImplTest.java index b9afcabbf..c88b9f0ba 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/MixedListUnivariateImplTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/MixedListUnivariateImplTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -48,7 +48,7 @@ public final class MixedListUnivariateImplTest extends TestCase { private double tolerance = 10E-15; private TransformerMap transformers = new TransformerMap(); - + public MixedListUnivariateImplTest(String name) { super(name); transformers = new TransformerMap(); @@ -106,7 +106,7 @@ public final class MixedListUnivariateImplTest extends TestCase { assertTrue( "Mean of n = 1 set should be value of single item n1, instead it is " + u.getMean() , u.getMean() == one); - + assertTrue( "StdDev of n = 1 set should be zero, instead it is: " + u.getStandardDeviation(), diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/MultivariateSummaryStatisticsTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/MultivariateSummaryStatisticsTest.java index 77c76d576..b3ab93344 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/MultivariateSummaryStatisticsTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/MultivariateSummaryStatisticsTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,7 +38,7 @@ public class MultivariateSummaryStatisticsTest extends TestCase { public MultivariateSummaryStatisticsTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(MultivariateSummaryStatisticsTest.class); suite.setName("MultivariateSummaryStatistics tests"); @@ -73,7 +73,7 @@ public class MultivariateSummaryStatisticsTest extends TestCase { assertEquals(3, u.getMean()[1], 1E-14); assertEquals(2, u.getDimension()); } - + public void testSetterIllegalState() throws Exception { MultivariateSummaryStatistics u = createMultivariateSummaryStatistics(2, true); u.addValue(new double[] { 1, 2 }); @@ -139,12 +139,12 @@ public class MultivariateSummaryStatisticsTest extends TestCase { TestUtils.assertEquals(reference.getGeometricMean(), shuffled.getSumLog(), 1.0e-10); } - + /** * Bogus mean implementation to test setter injection. * Returns the sum instead of the mean. */ - static class sumMean implements StorelessUnivariateStatistic { + static class sumMean implements StorelessUnivariateStatistic { private double sum = 0; private long n = 0; public double evaluate(double[] values, int begin, int length) { @@ -154,7 +154,7 @@ public class MultivariateSummaryStatisticsTest extends TestCase { return 0; } public void clear() { - sum = 0; + sum = 0; n = 0; } public long getN() { @@ -170,7 +170,7 @@ public class MultivariateSummaryStatisticsTest extends TestCase { public void incrementAll(double[] values, int start, int length) { } public void incrementAll(double[] values) { - } + } public StorelessUnivariateStatistic copy() { return new sumMean(); } @@ -216,8 +216,8 @@ public class MultivariateSummaryStatisticsTest extends TestCase { assertEquals(2.0 / 3.0, u.getCovariance().getEntry(1, 0), 1.0e-10); assertEquals(2.0 / 3.0, u.getCovariance().getEntry(1, 1), 1.0e-10); u.clear(); - assertEquals(0, u.getN()); - } + assertEquals(0, u.getN()); + } public void testN0andN1Conditions() throws Exception { MultivariateSummaryStatistics u = createMultivariateSummaryStatistics(1, true); @@ -230,7 +230,7 @@ public class MultivariateSummaryStatisticsTest extends TestCase { assertEquals(1.0, u.getGeometricMean()[0], 1.0e-10); assertEquals(0.0, u.getStandardDeviation()[0], 1.0e-10); - /* n=2 */ + /* n=2 */ u.addValue(new double[] { 2 }); assertTrue(u.getStandardDeviation()[0] > 0); @@ -238,15 +238,15 @@ public class MultivariateSummaryStatisticsTest extends TestCase { public void testNaNContracts() throws DimensionMismatchException { MultivariateSummaryStatistics u = createMultivariateSummaryStatistics(1, true); - assertTrue(Double.isNaN(u.getMean()[0])); - assertTrue(Double.isNaN(u.getMin()[0])); - assertTrue(Double.isNaN(u.getStandardDeviation()[0])); + assertTrue(Double.isNaN(u.getMean()[0])); + assertTrue(Double.isNaN(u.getMin()[0])); + assertTrue(Double.isNaN(u.getStandardDeviation()[0])); assertTrue(Double.isNaN(u.getGeometricMean()[0])); u.addValue(new double[] { 1.0 }); - assertFalse(Double.isNaN(u.getMean()[0])); - assertFalse(Double.isNaN(u.getMin()[0])); - assertFalse(Double.isNaN(u.getStandardDeviation()[0])); + assertFalse(Double.isNaN(u.getMean()[0])); + assertFalse(Double.isNaN(u.getMin()[0])); + assertFalse(Double.isNaN(u.getStandardDeviation()[0])); assertFalse(Double.isNaN(u.getGeometricMean()[0])); } @@ -302,7 +302,7 @@ public class MultivariateSummaryStatisticsTest extends TestCase { t.addValue(new double[] { 5d, 1d }); assertTrue(t.equals(u)); assertTrue(u.equals(t)); - assertEquals(u.hashCode(), t.hashCode()); + assertEquals(u.hashCode(), t.hashCode()); // Clear and make sure summaries are indistinguishable from empty summary u.clear(); diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/StatisticalSummaryValuesTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/StatisticalSummaryValuesTest.java index cf293a375..4810739ea 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/StatisticalSummaryValuesTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/StatisticalSummaryValuesTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,25 +29,25 @@ import org.apache.commons.math.TestUtils; */ public final class StatisticalSummaryValuesTest extends TestCase { - - + + public StatisticalSummaryValuesTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(StatisticalSummaryValuesTest.class); suite.setName("StatisticalSummaryValues Tests"); return suite; } - + public void testSerialization() { StatisticalSummaryValues u = new StatisticalSummaryValues(1, 2, 3, 4, 5, 6); - TestUtils.checkSerializedEquality(u); + TestUtils.checkSerializedEquality(u); StatisticalSummaryValues t = (StatisticalSummaryValues) TestUtils.serializeAndRecover(u); verifyEquality(u, t); } - + public void testEqualsAndHashCode() { StatisticalSummaryValues u = new StatisticalSummaryValues(1, 2, 3, 4, 5, 6); StatisticalSummaryValues t = null; @@ -57,13 +57,13 @@ public final class StatisticalSummaryValuesTest extends TestCase { t = new StatisticalSummaryValues(1, 2, 3, 4, 5, 6); assertTrue("instances with same data should be equal", t.equals(u)); assertEquals("hash code", u.hashCode(), t.hashCode()); - + u = new StatisticalSummaryValues(Double.NaN, 2, 3, 4, 5, 6); t = new StatisticalSummaryValues(1, Double.NaN, 3, 4, 5, 6); - assertFalse("instances based on different data should be different", + assertFalse("instances based on different data should be different", (u.equals(t) ||t.equals(u))); } - + private void verifyEquality(StatisticalSummaryValues s, StatisticalSummaryValues u) { assertEquals("N",s.getN(),u.getN()); TestUtils.assertEquals("sum",s.getSum(),u.getSum(), 0); @@ -71,6 +71,6 @@ public final class StatisticalSummaryValuesTest extends TestCase { TestUtils.assertEquals("std",s.getStandardDeviation(),u.getStandardDeviation(), 0); TestUtils.assertEquals("mean",s.getMean(),u.getMean(), 0); TestUtils.assertEquals("min",s.getMin(),u.getMin(), 0); - TestUtils.assertEquals("max",s.getMax(),u.getMax(), 0); + TestUtils.assertEquals("max",s.getMax(),u.getMax(), 0); } } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/StorelessUnivariateStatisticAbstractTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/StorelessUnivariateStatisticAbstractTest.java index 7a22ac639..8cb8b5835 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/StorelessUnivariateStatisticAbstractTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/StorelessUnivariateStatisticAbstractTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,7 @@ public abstract class StorelessUnivariateStatisticAbstractTest public StorelessUnivariateStatisticAbstractTest(String name) { super(name); } - + /** Small sample arrays */ protected double[][] smallSamples = {{}, {1}, {1,2}, {1,2,3}, {1,2,3,4}}; @@ -40,32 +40,32 @@ public abstract class StorelessUnivariateStatisticAbstractTest /**Expected value for the testArray defined in UnivariateStatisticAbstractTest */ @Override public abstract double expectedValue(); - - /** - * Verifies that increment() and incrementAll work properly. + + /** + * Verifies that increment() and incrementAll work properly. */ public void testIncrementation() throws Exception { StorelessUnivariateStatistic statistic = (StorelessUnivariateStatistic) getUnivariateStatistic(); - + // Add testArray one value at a time and check result for (int i = 0; i < testArray.length; i++) { statistic.increment(testArray[i]); } - + assertEquals(expectedValue(), statistic.getResult(), getTolerance()); assertEquals(testArray.length, statistic.getN()); statistic.clear(); - + // Add testArray all at once and check again statistic.incrementAll(testArray); assertEquals(expectedValue(), statistic.getResult(), getTolerance()); assertEquals(testArray.length, statistic.getN()); - + statistic.clear(); - + // Cleared assertTrue(Double.isNaN(statistic.getResult())); assertEquals(0, statistic.getN()); @@ -76,7 +76,7 @@ public abstract class StorelessUnivariateStatisticAbstractTest StorelessUnivariateStatistic statistic = (StorelessUnivariateStatistic) getUnivariateStatistic(); - + TestUtils.checkSerializedEquality(statistic); statistic.clear(); @@ -84,11 +84,11 @@ public abstract class StorelessUnivariateStatisticAbstractTest for (int i = 0; i < testArray.length; i++) { statistic.increment(testArray[i]); if(i % 5 == 0) - statistic = (StorelessUnivariateStatistic)TestUtils.serializeAndRecover(statistic); + statistic = (StorelessUnivariateStatistic)TestUtils.serializeAndRecover(statistic); } - + TestUtils.checkSerializedEquality(statistic); - + assertEquals(expectedValue(), statistic.getResult(), getTolerance()); statistic.clear(); @@ -96,53 +96,53 @@ public abstract class StorelessUnivariateStatisticAbstractTest assertTrue(Double.isNaN(statistic.getResult())); } - + public void testEqualsAndHashCode() { StorelessUnivariateStatistic statistic = (StorelessUnivariateStatistic) getUnivariateStatistic(); StorelessUnivariateStatistic statistic2 = null; - + assertTrue("non-null, compared to null", !statistic.equals(statistic2)); assertTrue("reflexive, non-null", statistic.equals(statistic)); - + int emptyHash = statistic.hashCode(); statistic2 = (StorelessUnivariateStatistic) getUnivariateStatistic(); assertTrue("empty stats should be equal", statistic.equals(statistic2)); - assertEquals("empty stats should have the same hashcode", + assertEquals("empty stats should have the same hashcode", emptyHash, statistic2.hashCode()); - + statistic.increment(1d); assertTrue("reflexive, non-empty", statistic.equals(statistic)); assertTrue("non-empty, compared to empty", !statistic.equals(statistic2)); assertTrue("non-empty, compared to empty", !statistic2.equals(statistic)); assertTrue("non-empty stat should have different hashcode from empty stat", statistic.hashCode() != emptyHash); - + statistic2.increment(1d); assertTrue("stats with same data should be equal", statistic.equals(statistic2)); - assertEquals("stats with same data should have the same hashcode", + assertEquals("stats with same data should have the same hashcode", statistic.hashCode(), statistic2.hashCode()); - + statistic.increment(Double.POSITIVE_INFINITY); assertTrue("stats with different n's should not be equal", !statistic2.equals(statistic)); assertTrue("stats with different n's should have different hashcodes", statistic.hashCode() != statistic2.hashCode()); - + statistic2.increment(Double.POSITIVE_INFINITY); assertTrue("stats with same data should be equal", statistic.equals(statistic2)); - assertEquals("stats with same data should have the same hashcode", - statistic.hashCode(), statistic2.hashCode()); - + assertEquals("stats with same data should have the same hashcode", + statistic.hashCode(), statistic2.hashCode()); + statistic.clear(); statistic2.clear(); assertTrue("cleared stats should be equal", statistic.equals(statistic2)); - assertEquals("cleared stats should have thashcode of empty stat", + assertEquals("cleared stats should have thashcode of empty stat", emptyHash, statistic2.hashCode()); - assertEquals("cleared stats should have thashcode of empty stat", + assertEquals("cleared stats should have thashcode of empty stat", emptyHash, statistic.hashCode()); - + } - + public void testMomentSmallSamples() { UnivariateStatistic stat = getUnivariateStatistic(); if (stat instanceof SecondMoment) { @@ -152,9 +152,9 @@ public abstract class StorelessUnivariateStatisticAbstractTest assertEquals(0d, moment.getResult(), 0); } } - - /** - * Make sure that evaluate(double[]) and inrementAll(double[]), + + /** + * Make sure that evaluate(double[]) and inrementAll(double[]), * getResult() give same results. */ public void testConsistency() { @@ -169,39 +169,39 @@ public abstract class StorelessUnivariateStatisticAbstractTest TestUtils.assertEquals(stat.getResult(), stat.evaluate(smallSamples[i]), getTolerance()); } } - + /** * Verifies that copied statistics remain equal to originals when * incremented the same way. * */ public void testCopyConsistency() { - + StorelessUnivariateStatistic master = (StorelessUnivariateStatistic) getUnivariateStatistic(); - + StorelessUnivariateStatistic replica = null; - + // Randomly select a portion of testArray to load first long index = Math.round((Math.random()) * testArray.length); - + // Put first half in master and copy master to replica master.incrementAll(testArray, 0, (int) index); replica = master.copy(); - + // Check same assertTrue(replica.equals(master)); assertTrue(master.equals(replica)); - + // Now add second part to both and check again - master.incrementAll(testArray, + master.incrementAll(testArray, (int) index, (int) (testArray.length - index)); - replica.incrementAll(testArray, + replica.incrementAll(testArray, (int) index, (int) (testArray.length - index)); assertTrue(replica.equals(master)); assertTrue(master.equals(replica)); } - + public void testSerial() { StorelessUnivariateStatistic s = (StorelessUnivariateStatistic) getUnivariateStatistic(); diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/SummaryStatisticsTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/SummaryStatisticsTest.java index a6a0a51d1..98cb25384 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/SummaryStatisticsTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/SummaryStatisticsTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -55,7 +55,7 @@ public class SummaryStatisticsTest extends TestCase { public SummaryStatisticsTest(String name) { super(name); } - + protected SummaryStatistics createSummaryStatistics() { return new SummaryStatistics(); } @@ -77,34 +77,34 @@ public class SummaryStatisticsTest extends TestCase { assertEquals("min",min,u.getMin(),tolerance); assertEquals("max",max,u.getMax(),tolerance); u.clear(); - assertEquals("total count",0,u.getN(),tolerance); - } + assertEquals("total count",0,u.getN(),tolerance); + } public void testN0andN1Conditions() throws Exception { SummaryStatistics u = createSummaryStatistics(); - assertTrue("Mean of n = 0 set should be NaN", + assertTrue("Mean of n = 0 set should be NaN", Double.isNaN( u.getMean() ) ); - assertTrue("Standard Deviation of n = 0 set should be NaN", + assertTrue("Standard Deviation of n = 0 set should be NaN", Double.isNaN( u.getStandardDeviation() ) ); - assertTrue("Variance of n = 0 set should be NaN", + assertTrue("Variance of n = 0 set should be NaN", Double.isNaN(u.getVariance() ) ); /* n=1 */ u.addValue(one); - assertTrue("mean should be one (n = 1)", + assertTrue("mean should be one (n = 1)", u.getMean() == one); - assertTrue("geometric should be one (n = 1) instead it is " + u.getGeometricMean(), + assertTrue("geometric should be one (n = 1) instead it is " + u.getGeometricMean(), u.getGeometricMean() == one); - assertTrue("Std should be zero (n = 1)", + assertTrue("Std should be zero (n = 1)", u.getStandardDeviation() == 0.0); - assertTrue("variance should be zero (n = 1)", + assertTrue("variance should be zero (n = 1)", u.getVariance() == 0.0); - /* n=2 */ + /* n=2 */ u.addValue(twoF); - assertTrue("Std should not be zero (n = 2)", + assertTrue("Std should not be zero (n = 2)", u.getStandardDeviation() != 0.0); - assertTrue("variance should not be zero (n = 2)", + assertTrue("variance should not be zero (n = 2)", u.getVariance() != 0.0); } @@ -116,25 +116,25 @@ public class SummaryStatisticsTest extends TestCase { u.addValue( 3.0 ); u.addValue( 4.0 ); - assertEquals( "Geometric mean not expected", 2.213364, + assertEquals( "Geometric mean not expected", 2.213364, u.getGeometricMean(), 0.00001 ); } public void testNaNContracts() { SummaryStatistics u = createSummaryStatistics(); - assertTrue("mean not NaN",Double.isNaN(u.getMean())); - assertTrue("min not NaN",Double.isNaN(u.getMin())); - assertTrue("std dev not NaN",Double.isNaN(u.getStandardDeviation())); - assertTrue("var not NaN",Double.isNaN(u.getVariance())); + assertTrue("mean not NaN",Double.isNaN(u.getMean())); + assertTrue("min not NaN",Double.isNaN(u.getMin())); + assertTrue("std dev not NaN",Double.isNaN(u.getStandardDeviation())); + assertTrue("var not NaN",Double.isNaN(u.getVariance())); assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); u.addValue(1.0); - assertEquals( "mean not expected", 1.0, + assertEquals( "mean not expected", 1.0, u.getMean(), Double.MIN_VALUE); - assertEquals( "variance not expected", 0.0, + assertEquals( "variance not expected", 0.0, u.getVariance(), Double.MIN_VALUE); - assertEquals( "geometric mean not expected", 1.0, + assertEquals( "geometric mean not expected", 1.0, u.getGeometricMean(), Double.MIN_VALUE); u.addValue(-1.0); @@ -160,7 +160,7 @@ public class SummaryStatisticsTest extends TestCase { verifySummary(u, summary); u.addValue(2d); summary = u.getSummary(); - verifySummary(u, summary); + verifySummary(u, summary); } public void testSerialization() { @@ -205,7 +205,7 @@ public class SummaryStatisticsTest extends TestCase { u.addValue(4d); assertFalse("different n's should make instances not equal", t.equals(u)); assertFalse("different n's should make instances not equal", u.equals(t)); - assertTrue("different n's should make hashcodes different", + assertTrue("different n's should make hashcodes different", u.hashCode() != t.hashCode()); //Add data in same order to t @@ -215,8 +215,8 @@ public class SummaryStatisticsTest extends TestCase { t.addValue(4d); assertTrue("summaries based on same data should be equal", t.equals(u)); assertTrue("summaries based on same data should be equal", u.equals(t)); - assertEquals("summaries based on same data should have same hashcodes", - u.hashCode(), t.hashCode()); + assertEquals("summaries based on same data should have same hashcodes", + u.hashCode(), t.hashCode()); // Clear and make sure summaries are indistinguishable from empty summary u.clear(); @@ -226,7 +226,7 @@ public class SummaryStatisticsTest extends TestCase { assertEquals("empty hash code", emptyHash, t.hashCode()); assertEquals("empty hash code", emptyHash, u.hashCode()); } - + public void testCopy() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.addValue(2d); @@ -244,7 +244,7 @@ public class SummaryStatisticsTest extends TestCase { assertTrue(v.sumsq == v.getSumsqImpl()); assertTrue(v.sumLog == v.getSumLogImpl()); assertTrue(v.variance == v.getVarianceImpl()); - + // Make sure both behave the same with additional values added u.addValue(7d); u.addValue(9d); @@ -256,14 +256,14 @@ public class SummaryStatisticsTest extends TestCase { v.addValue(23d); assertEquals(u, v); assertEquals(v, u); - + // Check implementation pointers are preserved u.clear(); u.setSumImpl(new Sum()); SummaryStatistics.copy(u,v); assertEquals(u.sum, v.sum); assertEquals(u.getSumImpl(), v.getSumImpl()); - + } private void verifySummary(SummaryStatistics u, StatisticalSummary s) { @@ -273,7 +273,7 @@ public class SummaryStatisticsTest extends TestCase { TestUtils.assertEquals("std",s.getStandardDeviation(),u.getStandardDeviation(),tolerance); TestUtils.assertEquals("mean",s.getMean(),u.getMean(),tolerance); TestUtils.assertEquals("min",s.getMin(),u.getMin(),tolerance); - TestUtils.assertEquals("max",s.getMax(),u.getMax(),tolerance); + TestUtils.assertEquals("max",s.getMax(),u.getMax(),tolerance); } public void testSetterInjection() throws Exception { @@ -292,7 +292,7 @@ public class SummaryStatisticsTest extends TestCase { u.clear(); u.setMeanImpl(new Mean()); // OK after clear } - + public void testSetterIllegalState() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.addValue(1); diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/UnivariateStatisticAbstractTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/UnivariateStatisticAbstractTest.java index 1845d1621..6a0af45eb 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/UnivariateStatisticAbstractTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/UnivariateStatisticAbstractTest.java @@ -56,7 +56,7 @@ public abstract class UnivariateStatisticAbstractTest extends TestCase { protected double weightedMean = 12.366995073891626d; - protected double weightedVar = 9.974760968886391d; + protected double weightedVar = 9.974760968886391d; protected double weightedStd = Math.sqrt(weightedVar); protected double weightedProduct = 8517647448765288000000d; protected double weightedSum = 251.05d; @@ -111,7 +111,7 @@ public abstract class UnivariateStatisticAbstractTest extends TestCase { copy.evaluate(testArray), getTolerance()); } - + /** * Tests consistency of weighted statistic computation. * For statistics that support weighted evaluation, this test case compares @@ -120,9 +120,9 @@ public abstract class UnivariateStatisticAbstractTest extends TestCase { * value appearing only once but with a weight value equal to its multiplicity * in the repeating array. */ - + public void testWeightedConsistency() throws Exception { - + // See if this statistic computes weighted statistics // If not, skip this test UnivariateStatistic statistic = getUnivariateStatistic(); @@ -133,23 +133,23 @@ public abstract class UnivariateStatisticAbstractTest extends TestCase { } catch (NoSuchMethodException ex) { return; // skip test } - + // Create arrays of values and corresponding integral weights // and longer array with values repeated according to the weights final int len = 10; // length of values array final double mu = 0; // mean of test data - final double sigma = 5; // std dev of test data + final double sigma = 5; // std dev of test data double[] values = new double[len]; double[] weights = new double[len]; - RandomData randomData = new RandomDataImpl(); - + RandomData randomData = new RandomDataImpl(); + // Fill weights array with random int values between 1 and 5 int[] intWeights = new int[len]; for (int i = 0; i < len; i++) { intWeights[i] = randomData.nextInt(1, 5); weights[i] = intWeights[i]; } - + // Fill values array with random data from N(mu, sigma) // and fill valuesList with values from values array with // values[i] repeated weights[i] times, each i @@ -161,21 +161,21 @@ public abstract class UnivariateStatisticAbstractTest extends TestCase { valuesList.add(new Double(value)); } } - + // Dump valuesList into repeatedValues array int sumWeights = valuesList.size(); double[] repeatedValues = new double[sumWeights]; for (int i = 0; i < sumWeights; i++) { repeatedValues[i] = valuesList.get(i); } - + // Compare result of weighted statistic computation with direct computation // on array of repeated values double weightedResult = (Double) evaluateMethod.invoke( statistic, values, weights, 0, values.length); TestUtils.assertRelativelyEquals( - statistic.evaluate(repeatedValues), weightedResult, 10E-14); - + statistic.evaluate(repeatedValues), weightedResult, 10E-14); + } } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/FirstMomentTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/FirstMomentTest.java index 6a5f4397b..719d902a6 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/FirstMomentTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/FirstMomentTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,14 +27,14 @@ public class FirstMomentTest extends StorelessUnivariateStatisticAbstractTest{ /** descriptive statistic. */ protected FirstMoment stat; - + /** * @param name */ public FirstMomentTest(String name) { super(name); } - + /** * @see org.apache.commons.math.stat.descriptive.UnivariateStatisticAbstractTest#getUnivariateStatistic() */ diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/FourthMomentTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/FourthMomentTest.java index 17eb6fda7..fe64c40e4 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/FourthMomentTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/FourthMomentTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,14 +27,14 @@ public class FourthMomentTest extends StorelessUnivariateStatisticAbstractTest{ /** descriptive statistic. */ protected FourthMoment stat; - + /** * @param name */ public FourthMomentTest(String name) { super(name); } - + /** * @see org.apache.commons.math.stat.descriptive.UnivariateStatisticAbstractTest#getUnivariateStatistic() */ diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/GeometricMeanTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/GeometricMeanTest.java index 156856772..4a8d6d783 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/GeometricMeanTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/GeometricMeanTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,7 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatistic; public class GeometricMeanTest extends StorelessUnivariateStatisticAbstractTest{ protected GeometricMean stat; - + /** * @param name */ @@ -42,7 +42,7 @@ public class GeometricMeanTest extends StorelessUnivariateStatisticAbstractTest{ suite.setName("Mean Tests"); return suite; } - + /** * {@inheritDoc} */ @@ -58,32 +58,32 @@ public class GeometricMeanTest extends StorelessUnivariateStatisticAbstractTest{ public double expectedValue() { return this.geoMean; } - + public void testSpecialValues() { GeometricMean mean = new GeometricMean(); // empty assertTrue(Double.isNaN(mean.getResult())); - + // finite data mean.increment(1d); assertFalse(Double.isNaN(mean.getResult())); - + // add 0 -- makes log sum blow to minus infinity, should make 0 mean.increment(0d); assertEquals(0d, mean.getResult(), 0); - + // add positive infinity - note the minus infinity above mean.increment(Double.POSITIVE_INFINITY); assertTrue(Double.isNaN(mean.getResult())); - + // clear mean.clear(); assertTrue(Double.isNaN(mean.getResult())); - + // positive infinity by itself mean.increment(Double.POSITIVE_INFINITY); assertEquals(Double.POSITIVE_INFINITY, mean.getResult(), 0); - + // negative value -- should make NaN mean.increment(-2d); assertTrue(Double.isNaN(mean.getResult())); diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/KurtosisTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/KurtosisTest.java index 0ca018386..5ff38bb3d 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/KurtosisTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/KurtosisTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,14 +29,14 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatistic; public class KurtosisTest extends StorelessUnivariateStatisticAbstractTest{ protected Kurtosis stat; - + /** * @param name */ public KurtosisTest(String name) { super(name); } - + public static Test suite() { TestSuite suite = new TestSuite(KurtosisTest.class); suite.setName("Kurtosis Tests"); @@ -58,7 +58,7 @@ public class KurtosisTest extends StorelessUnivariateStatisticAbstractTest{ public double expectedValue() { return this.kurt; } - + /** * Make sure Double.NaN is returned iff n < 4 * @@ -73,7 +73,7 @@ public class KurtosisTest extends StorelessUnivariateStatisticAbstractTest{ kurt.increment(1d); assertTrue(Double.isNaN(kurt.getResult())); kurt.increment(1d); - assertFalse(Double.isNaN(kurt.getResult())); + assertFalse(Double.isNaN(kurt.getResult())); } } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/SecondMomentTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/SecondMomentTest.java index a8cfb3903..0f65414d4 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/SecondMomentTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/SecondMomentTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,14 +27,14 @@ public class SecondMomentTest extends StorelessUnivariateStatisticAbstractTest { /** descriptive statistic. */ protected SecondMoment stat; - + /** * @param name */ public SecondMomentTest(String name) { super(name); } - + /** * @see org.apache.commons.math.stat.descriptive.UnivariateStatisticAbstractTest#getUnivariateStatistic() */ diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/SkewnessTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/SkewnessTest.java index 0fbda69ca..933aea43e 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/SkewnessTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/SkewnessTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,13 +24,13 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatistic; /** * Test cases for the {@link UnivariateStatistic} class. - * + * * @version $Revision$ $Date$ */ public class SkewnessTest extends StorelessUnivariateStatisticAbstractTest{ protected Skewness stat; - + /** * @param name */ @@ -51,7 +51,7 @@ public class SkewnessTest extends StorelessUnivariateStatisticAbstractTest{ suite.setName("Skewness Tests"); return suite; } - + /** * {@inheritDoc} */ @@ -59,7 +59,7 @@ public class SkewnessTest extends StorelessUnivariateStatisticAbstractTest{ public double expectedValue() { return this.skew; } - + /** * Make sure Double.NaN is returned iff n < 3 * @@ -72,7 +72,7 @@ public class SkewnessTest extends StorelessUnivariateStatisticAbstractTest{ skew.increment(1d); assertTrue(Double.isNaN(skew.getResult())); skew.increment(1d); - assertFalse(Double.isNaN(skew.getResult())); + assertFalse(Double.isNaN(skew.getResult())); } } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/StandardDeviationTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/StandardDeviationTest.java index c60acaf83..f2b14028d 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/StandardDeviationTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/StandardDeviationTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,13 +24,13 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatistic; /** * Test cases for the {@link UnivariateStatistic} class. - * + * * @version $Revision$ $Date$ */ public class StandardDeviationTest extends StorelessUnivariateStatisticAbstractTest{ protected StandardDeviation stat; - + /** * @param name */ @@ -51,7 +51,7 @@ public class StandardDeviationTest extends StorelessUnivariateStatisticAbstractT suite.setName("StandardDeviation Tests"); return suite; } - + /** * {@inheritDoc} */ @@ -59,7 +59,7 @@ public class StandardDeviationTest extends StorelessUnivariateStatisticAbstractT public double expectedValue() { return this.std; } - + /** * Make sure Double.NaN is returned iff n = 0 * @@ -70,10 +70,10 @@ public class StandardDeviationTest extends StorelessUnivariateStatisticAbstractT std.increment(1d); assertEquals(0d, std.getResult(), 0); } - + /** * Test population version of variance - */ + */ public void testPopulation() { double[] values = {-1.0d, 3.1d, 4.0d, -2.1d, 22d, 11.7d, 3d, 14d}; double sigma = populationStandardDeviation(values); @@ -85,13 +85,13 @@ public class StandardDeviationTest extends StorelessUnivariateStatisticAbstractT s1.incrementAll(values); assertEquals(sigma, s1.getResult(), 1E-14); s1 = new StandardDeviation(false, m); - assertEquals(sigma, s1.getResult(), 1E-14); + assertEquals(sigma, s1.getResult(), 1E-14); s1 = new StandardDeviation(false); assertEquals(sigma, s1.evaluate(values), 1E-14); s1.incrementAll(values); - assertEquals(sigma, s1.getResult(), 1E-14); + assertEquals(sigma, s1.getResult(), 1E-14); } - + /** * Definitional formula for population standard deviation */ @@ -99,7 +99,7 @@ public class StandardDeviationTest extends StorelessUnivariateStatisticAbstractT double mean = new Mean().evaluate(v); double sum = 0; for (int i = 0; i < v.length; i++) { - sum += (v[i] - mean) * (v[i] - mean); + sum += (v[i] - mean) * (v[i] - mean); } return Math.sqrt(sum / v.length); } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/ThirdMomentTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/ThirdMomentTest.java index bd66fddeb..b5f9e41ff 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/ThirdMomentTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/ThirdMomentTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,14 +27,14 @@ public class ThirdMomentTest extends StorelessUnivariateStatisticAbstractTest{ /** descriptive statistic. */ protected ThirdMoment stat; - + /** * @param name */ public ThirdMomentTest(String name) { super(name); } - + /** * @see org.apache.commons.math.stat.descriptive.UnivariateStatisticAbstractTest#getUnivariateStatistic() */ diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/VarianceTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/VarianceTest.java index 29846b62d..65e1fa7c3 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/VarianceTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/VarianceTest.java @@ -25,13 +25,13 @@ import org.apache.commons.math.util.MathUtils; /** * Test cases for the {@link UnivariateStatistic} class. - * + * * @version $Revision$ $Date$ */ public class VarianceTest extends StorelessUnivariateStatisticAbstractTest{ protected Variance stat; - + /** * @param name */ @@ -111,19 +111,19 @@ public class VarianceTest extends StorelessUnivariateStatisticAbstractTest{ public void testWeightedVariance() { Variance variance = new Variance(); - assertEquals(expectedWeightedValue(), + assertEquals(expectedWeightedValue(), variance.evaluate(testArray, testWeightsArray, 0, testArray.length), getTolerance()); - + // All weights = 1 -> weighted variance = unweighted variance assertEquals(expectedValue(), variance.evaluate(testArray, unitWeightsArray, 0, testArray.length), getTolerance()); - + // All weights the same -> when weights are normalized to sum to the length of the values array, // weighted variance = unweighted value assertEquals(expectedValue(), variance.evaluate(testArray, MathUtils.normalizeArray(identicalWeightsArray, testArray.length), 0, testArray.length), getTolerance()); - + } } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/moment/VectorialCovarianceTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/moment/VectorialCovarianceTest.java index ed790e33e..cdf0c37f3 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/moment/VectorialCovarianceTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/moment/VectorialCovarianceTest.java @@ -83,7 +83,7 @@ extends TestCase { VectorialCovariance stat = new VectorialCovariance(points[0].length, true); assertEquals(stat, TestUtils.serializeAndRecover(stat)); } - + @Override public void setUp() { points = new double[][] { diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/rank/MaxTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/rank/MaxTest.java index 32d874023..f24e22638 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/rank/MaxTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/rank/MaxTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,7 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatistic; public class MaxTest extends StorelessUnivariateStatisticAbstractTest{ protected Max stat; - + /** * @param name */ @@ -42,7 +42,7 @@ public class MaxTest extends StorelessUnivariateStatisticAbstractTest{ suite.setName("Max Tests"); return suite; } - + /** * {@inheritDoc} */ @@ -58,9 +58,9 @@ public class MaxTest extends StorelessUnivariateStatisticAbstractTest{ public double expectedValue() { return this.max; } - + public void testSpecialValues() { - double[] testArray = {0d, Double.NaN, Double.NEGATIVE_INFINITY, + double[] testArray = {0d, Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY}; Max max = new Max(); assertTrue(Double.isNaN(max.getResult())); @@ -72,16 +72,16 @@ public class MaxTest extends StorelessUnivariateStatisticAbstractTest{ assertEquals(0d, max.getResult(), 0); max.increment(testArray[3]); assertEquals(Double.POSITIVE_INFINITY, max.getResult(), 0); - assertEquals(Double.POSITIVE_INFINITY, max.evaluate(testArray), 0); + assertEquals(Double.POSITIVE_INFINITY, max.evaluate(testArray), 0); } public void testNaNs() { Max max = new Max(); double nan = Double.NaN; - assertEquals(3d, max.evaluate(new double[]{nan, 2d, 3d}), 0); - assertEquals(3d, max.evaluate(new double[]{1d, nan, 3d}), 0); - assertEquals(2d, max.evaluate(new double[]{1d, 2d, nan}), 0); - assertTrue(Double.isNaN(max.evaluate(new double[]{nan, nan, nan}))); + assertEquals(3d, max.evaluate(new double[]{nan, 2d, 3d}), 0); + assertEquals(3d, max.evaluate(new double[]{1d, nan, 3d}), 0); + assertEquals(2d, max.evaluate(new double[]{1d, 2d, nan}), 0); + assertTrue(Double.isNaN(max.evaluate(new double[]{nan, nan, nan}))); } } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/rank/MedianTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/rank/MedianTest.java index 7cc1f18fb..62b5908c2 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/rank/MedianTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/rank/MedianTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,7 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatisticAbstractTest; public class MedianTest extends UnivariateStatisticAbstractTest{ protected Median stat; - + /** * @param name */ @@ -42,12 +42,12 @@ public class MedianTest extends UnivariateStatisticAbstractTest{ suite.setName("Median Tests"); return suite; } - + /** * {@inheritDoc} */ @Override - public UnivariateStatistic getUnivariateStatistic() { + public UnivariateStatistic getUnivariateStatistic() { return new Median(); } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/rank/MinTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/rank/MinTest.java index 819e656a9..b727fb60e 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/rank/MinTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/rank/MinTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,7 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatistic; public class MinTest extends StorelessUnivariateStatisticAbstractTest{ protected Min stat; - + /** * @param name */ @@ -42,7 +42,7 @@ public class MinTest extends StorelessUnivariateStatisticAbstractTest{ suite.setName("Min Tests"); return suite; } - + /** * {@inheritDoc} */ @@ -58,9 +58,9 @@ public class MinTest extends StorelessUnivariateStatisticAbstractTest{ public double expectedValue() { return this.min; } - + public void testSpecialValues() { - double[] testArray = {0d, Double.NaN, Double.POSITIVE_INFINITY, + double[] testArray = {0d, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}; Min min = new Min(); assertTrue(Double.isNaN(min.getResult())); @@ -72,16 +72,16 @@ public class MinTest extends StorelessUnivariateStatisticAbstractTest{ assertEquals(0d, min.getResult(), 0); min.increment(testArray[3]); assertEquals(Double.NEGATIVE_INFINITY, min.getResult(), 0); - assertEquals(Double.NEGATIVE_INFINITY, min.evaluate(testArray), 0); + assertEquals(Double.NEGATIVE_INFINITY, min.evaluate(testArray), 0); } public void testNaNs() { Min min = new Min(); double nan = Double.NaN; - assertEquals(2d, min.evaluate(new double[]{nan, 2d, 3d}), 0); - assertEquals(1d, min.evaluate(new double[]{1d, nan, 3d}), 0); - assertEquals(1d, min.evaluate(new double[]{1d, 2d, nan}), 0); - assertTrue(Double.isNaN(min.evaluate(new double[]{nan, nan, nan}))); + assertEquals(2d, min.evaluate(new double[]{nan, 2d, 3d}), 0); + assertEquals(1d, min.evaluate(new double[]{1d, nan, 3d}), 0); + assertEquals(1d, min.evaluate(new double[]{1d, 2d, nan}), 0); + assertTrue(Double.isNaN(min.evaluate(new double[]{nan, nan, nan}))); } - + } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/rank/PercentileTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/rank/PercentileTest.java index e6abe440d..8112551cf 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/rank/PercentileTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/rank/PercentileTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,7 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatisticAbstractTest; public class PercentileTest extends UnivariateStatisticAbstractTest{ protected Percentile stat; - + /** * @param name */ @@ -42,12 +42,12 @@ public class PercentileTest extends UnivariateStatisticAbstractTest{ suite.setName("Percentile Tests"); return suite; } - + /** * {@inheritDoc} */ @Override - public UnivariateStatistic getUnivariateStatistic() { + public UnivariateStatistic getUnivariateStatistic() { return new Percentile(95.0); } @@ -64,7 +64,7 @@ public class PercentileTest extends UnivariateStatisticAbstractTest{ Percentile p = new Percentile(75); assertEquals(3.0, p.evaluate(d), 1.0e-5); } - + public void testPercentile() { double[] d = new double[] {1, 3, 2, 4}; Percentile p = new Percentile(30); @@ -75,7 +75,7 @@ public class PercentileTest extends UnivariateStatisticAbstractTest{ assertEquals(3.75, p.evaluate(d), 1.0e-5); p.setQuantile(50); assertEquals(2.5, p.evaluate(d), 1.0e-5); - + // invalid percentiles try { p.evaluate(d, 0, d.length, -1.0); @@ -90,21 +90,21 @@ public class PercentileTest extends UnivariateStatisticAbstractTest{ // success } } - + public void testNISTExample() { - double[] d = new double[] {95.1772, 95.1567, 95.1937, 95.1959, + double[] d = new double[] {95.1772, 95.1567, 95.1937, 95.1959, 95.1442, 95.0610, 95.1591, 95.1195, 95.1772, 95.0925, 95.1990, 95.1682 }; - Percentile p = new Percentile(90); + Percentile p = new Percentile(90); assertEquals(95.1981, p.evaluate(d), 1.0e-4); assertEquals(95.1990, p.evaluate(d,0,d.length, 100d), 0); } - + public void test5() { Percentile percentile = new Percentile(5); assertEquals(this.percentile5, percentile.evaluate(testArray), getTolerance()); } - + public void testNullEmpty() { Percentile percentile = new Percentile(50); double[] nullArray = null; @@ -114,20 +114,20 @@ public class PercentileTest extends UnivariateStatisticAbstractTest{ fail("Expecting IllegalArgumentException for null array"); } catch (IllegalArgumentException ex) { // expected - } - assertTrue(Double.isNaN(percentile.evaluate(emptyArray))); + } + assertTrue(Double.isNaN(percentile.evaluate(emptyArray))); } - + public void testSingleton() { Percentile percentile = new Percentile(50); double[] singletonArray = new double[] {1d}; assertEquals(1d, percentile.evaluate(singletonArray), 0); assertEquals(1d, percentile.evaluate(singletonArray, 0, 1), 0); assertEquals(1d, percentile.evaluate(singletonArray, 0, 1, 5), 0); - assertEquals(1d, percentile.evaluate(singletonArray, 0, 1, 100), 0); - assertTrue(Double.isNaN(percentile.evaluate(singletonArray, 0, 0))); + assertEquals(1d, percentile.evaluate(singletonArray, 0, 1, 100), 0); + assertTrue(Double.isNaN(percentile.evaluate(singletonArray, 0, 0))); } - + public void testSpecialValues() { Percentile percentile = new Percentile(50); double[] specialValues = new double[] {0d, 1d, 2d, 3d, 4d, Double.NaN}; @@ -135,22 +135,22 @@ public class PercentileTest extends UnivariateStatisticAbstractTest{ specialValues = new double[] {Double.NEGATIVE_INFINITY, 1d, 2d, 3d, Double.NaN, Double.POSITIVE_INFINITY}; assertEquals(2.5d, percentile.evaluate(specialValues), 0); - specialValues = new double[] {1d, 1d, Double.POSITIVE_INFINITY, + specialValues = new double[] {1d, 1d, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}; assertTrue(Double.isInfinite(percentile.evaluate(specialValues))); - specialValues = new double[] {1d, 1d, Double.NaN, + specialValues = new double[] {1d, 1d, Double.NaN, Double.NaN}; assertTrue(Double.isNaN(percentile.evaluate(specialValues))); - specialValues = new double[] {1d, 1d, Double.NEGATIVE_INFINITY, + specialValues = new double[] {1d, 1d, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY}; // Interpolation results in NEGATIVE_INFINITY + POSITIVE_INFINITY - assertTrue(Double.isNaN(percentile.evaluate(specialValues))); + assertTrue(Double.isNaN(percentile.evaluate(specialValues))); } - + public void testSetQuantile() { Percentile percentile = new Percentile(10); percentile.setQuantile(100); // OK - assertEquals(100, percentile.getQuantile(), 0); + assertEquals(100, percentile.getQuantile(), 0); try { percentile.setQuantile(0); fail("Expecting IllegalArgumentException"); @@ -162,7 +162,7 @@ public class PercentileTest extends UnivariateStatisticAbstractTest{ fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } } - + } diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/summary/SumLogTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/summary/SumLogTest.java index 9c8db3086..28ed46745 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/summary/SumLogTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/summary/SumLogTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,7 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatistic; public class SumLogTest extends StorelessUnivariateStatisticAbstractTest{ protected SumOfLogs stat; - + /** * @param name */ @@ -42,12 +42,12 @@ public class SumLogTest extends StorelessUnivariateStatisticAbstractTest{ suite.setName("SumLog Tests"); return suite; } - + /** * {@inheritDoc} */ @Override - public UnivariateStatistic getUnivariateStatistic() { + public UnivariateStatistic getUnivariateStatistic() { return new SumOfLogs(); } @@ -58,32 +58,32 @@ public class SumLogTest extends StorelessUnivariateStatisticAbstractTest{ public double expectedValue() { return this.sumLog; } - + public void testSpecialValues() { SumOfLogs sum = new SumOfLogs(); // empty assertTrue(Double.isNaN(sum.getResult())); - + // finite data sum.increment(1d); assertFalse(Double.isNaN(sum.getResult())); - + // add negative infinity sum.increment(0d); assertEquals(Double.NEGATIVE_INFINITY, sum.getResult(), 0); - + // add positive infinity -- should make NaN sum.increment(Double.POSITIVE_INFINITY); assertTrue(Double.isNaN(sum.getResult())); - + // clear sum.clear(); assertTrue(Double.isNaN(sum.getResult())); - + // positive infinity by itself sum.increment(Double.POSITIVE_INFINITY); assertEquals(Double.POSITIVE_INFINITY, sum.getResult(), 0); - + // negative value -- should make NaN sum.increment(-2d); assertTrue(Double.isNaN(sum.getResult())); diff --git a/src/test/java/org/apache/commons/math/stat/descriptive/summary/SumSqTest.java b/src/test/java/org/apache/commons/math/stat/descriptive/summary/SumSqTest.java index 9edde045e..fb7975893 100644 --- a/src/test/java/org/apache/commons/math/stat/descriptive/summary/SumSqTest.java +++ b/src/test/java/org/apache/commons/math/stat/descriptive/summary/SumSqTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,13 +24,13 @@ import org.apache.commons.math.stat.descriptive.UnivariateStatistic; /** * Test cases for the {@link SumOfSquares} class. - * + * * @version $Revision$ $Date$ */ public class SumSqTest extends StorelessUnivariateStatisticAbstractTest{ protected SumOfSquares stat; - + /** * @param name */ @@ -43,7 +43,7 @@ public class SumSqTest extends StorelessUnivariateStatisticAbstractTest{ suite.setName("SumSq Tests"); return suite; } - + /** * {@inheritDoc} */ @@ -59,7 +59,7 @@ public class SumSqTest extends StorelessUnivariateStatisticAbstractTest{ public double expectedValue() { return this.sumSq; } - + public void testSpecialValues() { SumOfSquares sumSq = new SumOfSquares(); assertTrue(Double.isNaN(sumSq.getResult())); @@ -70,9 +70,9 @@ public class SumSqTest extends StorelessUnivariateStatisticAbstractTest{ sumSq.increment(Double.NEGATIVE_INFINITY); assertEquals(Double.POSITIVE_INFINITY, sumSq.getResult(), 0); sumSq.increment(Double.NaN); - assertTrue(Double.isNaN(sumSq.getResult())); + assertTrue(Double.isNaN(sumSq.getResult())); sumSq.increment(1); - assertTrue(Double.isNaN(sumSq.getResult())); + assertTrue(Double.isNaN(sumSq.getResult())); } } diff --git a/src/test/java/org/apache/commons/math/stat/inference/ChiSquareFactoryTest.java b/src/test/java/org/apache/commons/math/stat/inference/ChiSquareFactoryTest.java index 3c07d6f47..68f23472a 100644 --- a/src/test/java/org/apache/commons/math/stat/inference/ChiSquareFactoryTest.java +++ b/src/test/java/org/apache/commons/math/stat/inference/ChiSquareFactoryTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/test/java/org/apache/commons/math/stat/inference/ChiSquareTestTest.java b/src/test/java/org/apache/commons/math/stat/inference/ChiSquareTestTest.java index d11c11bf7..23f4fff95 100644 --- a/src/test/java/org/apache/commons/math/stat/inference/ChiSquareTestTest.java +++ b/src/test/java/org/apache/commons/math/stat/inference/ChiSquareTestTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -41,17 +41,17 @@ public class ChiSquareTestTest extends TestCase { } public void testChiSquare() throws Exception { - - // Target values computed using R version 1.8.1 - // Some assembly required ;-) + + // Target values computed using R version 1.8.1 + // Some assembly required ;-) // Use sum((obs - exp)^2/exp) for the chi-square statistic and // 1 - pchisq(sum((obs - exp)^2/exp), length(obs) - 1) for the p-value - + long[] observed = {10, 9, 11}; double[] expected = {10, 10, 10}; assertEquals("chi-square statistic", 0.2, testStatistic.chiSquare(expected, observed), 10E-12); assertEquals("chi-square p-value", 0.904837418036, testStatistic.chiSquareTest(expected, observed), 1E-10); - + long[] observed1 = { 500, 623, 72, 70, 31 }; double[] expected1 = { 485, 541, 82, 61, 37 }; assertEquals( "chi-square test statistic", 9.023307936427388, testStatistic.chiSquare(expected1, observed1), 1E-10); @@ -64,8 +64,8 @@ public class ChiSquareTestTest extends TestCase { fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + long[] tooShortObs = { 0 }; double[] tooShortEx = { 1 }; try { @@ -84,7 +84,7 @@ public class ChiSquareTestTest extends TestCase { } catch (IllegalArgumentException ex) { // expected } - + // 0 expected count expected[0] = 0; try { @@ -92,8 +92,8 @@ public class ChiSquareTestTest extends TestCase { fail("bad expected count, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + // negative observed count expected[0] = 1; observed[0] = -1; @@ -102,25 +102,25 @@ public class ChiSquareTestTest extends TestCase { fail("bad expected count, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + } public void testChiSquareIndependence() throws Exception { - - // Target values computed using R version 1.8.1 - + + // Target values computed using R version 1.8.1 + long[][] counts = { {40, 22, 43}, {91, 21, 28}, {60, 10, 22}}; assertEquals( "chi-square test statistic", 22.709027688, testStatistic.chiSquare(counts), 1E-9); assertEquals("chi-square p-value", 0.000144751460134, testStatistic.chiSquareTest(counts), 1E-9); assertTrue("chi-square test reject", testStatistic.chiSquareTest(counts, 0.0002)); - assertTrue("chi-square test accept", !testStatistic.chiSquareTest(counts, 0.0001)); - + assertTrue("chi-square test accept", !testStatistic.chiSquareTest(counts, 0.0001)); + long[][] counts2 = {{10, 15}, {30, 40}, {60, 90} }; assertEquals( "chi-square test statistic", 0.168965517241, testStatistic.chiSquare(counts2), 1E-9); assertEquals("chi-square p-value",0.918987499852, testStatistic.chiSquareTest(counts2), 1E-9); - assertTrue("chi-square test accept", !testStatistic.chiSquareTest(counts2, 0.1)); - + assertTrue("chi-square test accept", !testStatistic.chiSquareTest(counts2, 0.1)); + // ragged input array long[][] counts3 = { {40, 22, 43}, {91, 21, 28}, {60, 10}}; try { @@ -129,7 +129,7 @@ public class ChiSquareTestTest extends TestCase { } catch (IllegalArgumentException ex) { // expected } - + // insufficient data long[][] counts4 = {{40, 22, 43}}; try { @@ -137,15 +137,15 @@ public class ChiSquareTestTest extends TestCase { fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } long[][] counts5 = {{40}, {40}, {30}, {10}}; try { testStatistic.chiSquare(counts5); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } - + } + // negative counts long[][] counts6 = {{10, -2}, {30, 40}, {60, 90} }; try { @@ -153,20 +153,20 @@ public class ChiSquareTestTest extends TestCase { fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } - + } + // bad alpha try { testStatistic.chiSquareTest(counts, 0); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } } - + public void testChiSquareLargeTestStatistic() throws Exception { double[] exp = new double[] { - 3389119.5, 649136.6, 285745.4, 25357364.76, 11291189.78, 543628.0, + 3389119.5, 649136.6, 285745.4, 25357364.76, 11291189.78, 543628.0, 232921.0, 437665.75 }; @@ -174,58 +174,58 @@ public class ChiSquareTestTest extends TestCase { 2372383, 584222, 257170, 17750155, 7903832, 489265, 209628, 393899 }; org.apache.commons.math.stat.inference.ChiSquareTestImpl csti = - new org.apache.commons.math.stat.inference.ChiSquareTestImpl(); - double cst = csti.chiSquareTest(exp, obs); + new org.apache.commons.math.stat.inference.ChiSquareTestImpl(); + double cst = csti.chiSquareTest(exp, obs); assertEquals("chi-square p-value", 0.0, cst, 1E-3); - assertEquals( "chi-square test statistic", + assertEquals( "chi-square test statistic", 114875.90421929007, testStatistic.chiSquare(exp, obs), 1E-9); } - + /** Contingency table containing zeros - PR # 32531 */ public void testChiSquareZeroCount() throws Exception { - // Target values computed using R version 1.8.1 + // Target values computed using R version 1.8.1 long[][] counts = { {40, 0, 4}, {91, 1, 2}, {60, 2, 0}}; assertEquals( "chi-square test statistic", 9.67444662263, testStatistic.chiSquare(counts), 1E-9); assertEquals("chi-square p-value", 0.0462835770603, - testStatistic.chiSquareTest(counts), 1E-9); + testStatistic.chiSquareTest(counts), 1E-9); } - + /** Target values verified using DATAPLOT version 2006.3 */ public void testChiSquareDataSetsComparisonEqualCounts() throws Exception { long[] observed1 = {10, 12, 12, 10}; - long[] observed2 = {5, 15, 14, 10}; - assertEquals("chi-square p value", 0.541096, + long[] observed2 = {5, 15, 14, 10}; + assertEquals("chi-square p value", 0.541096, testStatistic.chiSquareTestDataSetsComparison( observed1, observed2), 1E-6); assertEquals("chi-square test statistic", 2.153846, testStatistic.chiSquareDataSetsComparison( observed1, observed2), 1E-6); - assertFalse("chi-square test result", + assertFalse("chi-square test result", testStatistic.chiSquareTestDataSetsComparison( observed1, observed2, 0.4)); } - + /** Target values verified using DATAPLOT version 2006.3 */ public void testChiSquareDataSetsComparisonUnEqualCounts() throws Exception { long[] observed1 = {10, 12, 12, 10, 15}; - long[] observed2 = {15, 10, 10, 15, 5}; - assertEquals("chi-square p value", 0.124115, + long[] observed2 = {15, 10, 10, 15, 5}; + assertEquals("chi-square p value", 0.124115, testStatistic.chiSquareTestDataSetsComparison( observed1, observed2), 1E-6); assertEquals("chi-square test statistic", 7.232189, testStatistic.chiSquareDataSetsComparison( observed1, observed2), 1E-6); - assertTrue("chi-square test result", + assertTrue("chi-square test result", testStatistic.chiSquareTestDataSetsComparison( observed1, observed2, 0.13)); - assertFalse("chi-square test result", + assertFalse("chi-square test result", testStatistic.chiSquareTestDataSetsComparison( observed1, observed2, 0.12)); } - + public void testChiSquareDataSetsComparisonBadCounts() throws Exception { long[] observed1 = {10, -1, 12, 10, 15}; diff --git a/src/test/java/org/apache/commons/math/stat/inference/OneWayAnovaTest.java b/src/test/java/org/apache/commons/math/stat/inference/OneWayAnovaTest.java index d0b44ffcc..5be5de671 100644 --- a/src/test/java/org/apache/commons/math/stat/inference/OneWayAnovaTest.java +++ b/src/test/java/org/apache/commons/math/stat/inference/OneWayAnovaTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ import java.util.List; public class OneWayAnovaTest extends TestCase { protected OneWayAnova testStatistic = new OneWayAnovaImpl(); - + private double[] emptyArray = {}; private double[] classA = @@ -65,7 +65,7 @@ public class OneWayAnovaTest extends TestCase { List twoClasses = new ArrayList(); twoClasses.add(classA); twoClasses.add(classB); - + assertEquals("ANOVA F-value", 0.0150579150579, testStatistic.anovaFValue(twoClasses), 1E-12); @@ -77,7 +77,7 @@ public class OneWayAnovaTest extends TestCase { fail("empty array for key classX, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } + } List tooFew = new ArrayList(); tooFew.add(classA); @@ -86,9 +86,9 @@ public class OneWayAnovaTest extends TestCase { fail("less than two classes, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } + } } - + public void testAnovaPValue() throws Exception { // Target comparison values computed using R version 2.6.0 (Linux version) @@ -103,7 +103,7 @@ public class OneWayAnovaTest extends TestCase { List twoClasses = new ArrayList(); twoClasses.add(classA); twoClasses.add(classB); - + assertEquals("ANOVA P-value", 0.904212960464, testStatistic.anovaPValue(twoClasses), 1E-12); @@ -121,8 +121,8 @@ public class OneWayAnovaTest extends TestCase { List twoClasses = new ArrayList(); twoClasses.add(classA); twoClasses.add(classB); - + assertFalse("ANOVA Test P>0.01", testStatistic.anovaTest(twoClasses, 0.01)); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/math/stat/inference/TTestFactoryTest.java b/src/test/java/org/apache/commons/math/stat/inference/TTestFactoryTest.java index ae6cffe42..313f4daec 100644 --- a/src/test/java/org/apache/commons/math/stat/inference/TTestFactoryTest.java +++ b/src/test/java/org/apache/commons/math/stat/inference/TTestFactoryTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/test/java/org/apache/commons/math/stat/inference/TTestTest.java b/src/test/java/org/apache/commons/math/stat/inference/TTestTest.java index 8bb4df272..c7320eff7 100644 --- a/src/test/java/org/apache/commons/math/stat/inference/TTestTest.java +++ b/src/test/java/org/apache/commons/math/stat/inference/TTestTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,11 +30,11 @@ import org.apache.commons.math.stat.descriptive.SummaryStatistics; public class TTestTest extends TestCase { protected TTest testStatistic = new TTestImpl(); - + private double[] tooShortObs = { 1.0 }; private double[] emptyObs = {}; - private SummaryStatistics emptyStats = new SummaryStatistics(); - SummaryStatistics tooShortStats = null; + private SummaryStatistics emptyStats = new SummaryStatistics(); + SummaryStatistics tooShortStats = null; public TTestTest(String name) { super(name); @@ -92,7 +92,7 @@ public class TTestTest extends TestCase { } catch (IllegalArgumentException ex) { // expected } - + try { testStatistic.t(mu, emptyStats); fail("arguments too short, IllegalArgumentException expected"); @@ -111,7 +111,7 @@ public class TTestTest extends TestCase { fail("insufficient data to perform t test, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } + } try { testStatistic.t(mu, tooShortStats); @@ -124,20 +124,20 @@ public class TTestTest extends TestCase { fail("insufficient data to perform t test, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } + } } - + public void testOneSampleTTest() throws Exception { double[] oneSidedP = {2d, 0d, 6d, 6d, 3d, 3d, 2d, 3d, -6d, 6d, 6d, 6d, 3d, 0d, 1d, 1d, 0d, 2d, 3d, 3d }; - SummaryStatistics oneSidedPStats = new SummaryStatistics(); + SummaryStatistics oneSidedPStats = new SummaryStatistics(); for (int i = 0; i < oneSidedP.length; i++) { oneSidedPStats.addValue(oneSidedP[i]); } // Target comparison values computed using R version 1.8.1 (Linux version) - assertEquals("one sample t stat", 3.86485535541, + assertEquals("one sample t stat", 3.86485535541, testStatistic.t(0d, oneSidedP), 10E-10); - assertEquals("one sample t stat", 3.86485535541, + assertEquals("one sample t stat", 3.86485535541, testStatistic.t(0d, oneSidedPStats),1E-10); assertEquals("one sample p value", 0.000521637019637, testStatistic.tTest(0d, oneSidedP) / 2d, 10E-10); @@ -147,102 +147,102 @@ public class TTestTest extends TestCase { assertTrue("one sample t-test reject", testStatistic.tTest(0d, oneSidedPStats, 0.01)); assertTrue("one sample t-test accept", !testStatistic.tTest(0d, oneSidedP, 0.0001)); assertTrue("one sample t-test accept", !testStatistic.tTest(0d, oneSidedPStats, 0.0001)); - + try { testStatistic.tTest(0d, oneSidedP, 95); fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { testStatistic.tTest(0d, oneSidedPStats, 95); fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + } - + public void testTwoSampleTHeterscedastic() throws Exception { double[] sample1 = { 7d, -4d, 18d, 17d, -3d, -5d, 1d, 10d, 11d, -2d }; double[] sample2 = { -1d, 12d, -1d, -3d, 3d, -5d, 5d, 2d, -11d, -1d, -3d }; - SummaryStatistics sampleStats1 = new SummaryStatistics(); + SummaryStatistics sampleStats1 = new SummaryStatistics(); for (int i = 0; i < sample1.length; i++) { sampleStats1.addValue(sample1[i]); } - SummaryStatistics sampleStats2 = new SummaryStatistics(); + SummaryStatistics sampleStats2 = new SummaryStatistics(); for (int i = 0; i < sample2.length; i++) { sampleStats2.addValue(sample2[i]); } - + // Target comparison values computed using R version 1.8.1 (Linux version) - assertEquals("two sample heteroscedastic t stat", 1.60371728768, + assertEquals("two sample heteroscedastic t stat", 1.60371728768, testStatistic.t(sample1, sample2), 1E-10); - assertEquals("two sample heteroscedastic t stat", 1.60371728768, + assertEquals("two sample heteroscedastic t stat", 1.60371728768, testStatistic.t(sampleStats1, sampleStats2), 1E-10); - assertEquals("two sample heteroscedastic p value", 0.128839369622, + assertEquals("two sample heteroscedastic p value", 0.128839369622, testStatistic.tTest(sample1, sample2), 1E-10); - assertEquals("two sample heteroscedastic p value", 0.128839369622, - testStatistic.tTest(sampleStats1, sampleStats2), 1E-10); - assertTrue("two sample heteroscedastic t-test reject", + assertEquals("two sample heteroscedastic p value", 0.128839369622, + testStatistic.tTest(sampleStats1, sampleStats2), 1E-10); + assertTrue("two sample heteroscedastic t-test reject", testStatistic.tTest(sample1, sample2, 0.2)); - assertTrue("two sample heteroscedastic t-test reject", + assertTrue("two sample heteroscedastic t-test reject", testStatistic.tTest(sampleStats1, sampleStats2, 0.2)); - assertTrue("two sample heteroscedastic t-test accept", + assertTrue("two sample heteroscedastic t-test accept", !testStatistic.tTest(sample1, sample2, 0.1)); - assertTrue("two sample heteroscedastic t-test accept", + assertTrue("two sample heteroscedastic t-test accept", !testStatistic.tTest(sampleStats1, sampleStats2, 0.1)); - + try { testStatistic.tTest(sample1, sample2, .95); fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { testStatistic.tTest(sampleStats1, sampleStats2, .95); fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { - // expected - } - + // expected + } + try { testStatistic.tTest(sample1, tooShortObs, .01); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { testStatistic.tTest(sampleStats1, tooShortStats, .01); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { testStatistic.tTest(sample1, tooShortObs); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { testStatistic.tTest(sampleStats1, tooShortStats); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { testStatistic.t(sample1, tooShortObs); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected } - + try { testStatistic.t(sampleStats1, tooShortStats); fail("insufficient data, IllegalArgumentException expected"); @@ -253,37 +253,37 @@ public class TTestTest extends TestCase { public void testTwoSampleTHomoscedastic() throws Exception { double[] sample1 ={2, 4, 6, 8, 10, 97}; double[] sample2 = {4, 6, 8, 10, 16}; - SummaryStatistics sampleStats1 = new SummaryStatistics(); + SummaryStatistics sampleStats1 = new SummaryStatistics(); for (int i = 0; i < sample1.length; i++) { sampleStats1.addValue(sample1[i]); } - SummaryStatistics sampleStats2 = new SummaryStatistics(); + SummaryStatistics sampleStats2 = new SummaryStatistics(); for (int i = 0; i < sample2.length; i++) { sampleStats2.addValue(sample2[i]); } - + // Target comparison values computed using R version 1.8.1 (Linux version) - assertEquals("two sample homoscedastic t stat", 0.73096310086, + assertEquals("two sample homoscedastic t stat", 0.73096310086, testStatistic.homoscedasticT(sample1, sample2), 10E-11); - assertEquals("two sample homoscedastic p value", 0.4833963785, - testStatistic.homoscedasticTTest(sampleStats1, sampleStats2), 1E-10); - assertTrue("two sample homoscedastic t-test reject", + assertEquals("two sample homoscedastic p value", 0.4833963785, + testStatistic.homoscedasticTTest(sampleStats1, sampleStats2), 1E-10); + assertTrue("two sample homoscedastic t-test reject", testStatistic.homoscedasticTTest(sample1, sample2, 0.49)); - assertTrue("two sample homoscedastic t-test accept", + assertTrue("two sample homoscedastic t-test accept", !testStatistic.homoscedasticTTest(sample1, sample2, 0.48)); } - + public void testSmallSamples() throws Exception { double[] sample1 = {1d, 3d}; - double[] sample2 = {4d, 5d}; - + double[] sample2 = {4d, 5d}; + // Target values computed using R, version 1.8.1 (linux version) assertEquals(-2.2360679775, testStatistic.t(sample1, sample2), 1E-10); assertEquals(0.198727388935, testStatistic.tTest(sample1, sample2), 1E-10); } - + public void testPaired() throws Exception { double[] sample1 = {1d, 3d, 5d, 7d}; double[] sample2 = {0d, 6d, 11d, 2d}; @@ -294,6 +294,6 @@ public class TTestTest extends TestCase { assertEquals(0.774544295819, testStatistic.pairedTTest(sample1, sample2), 1E-10); assertEquals(0.001208, testStatistic.pairedTTest(sample1, sample3), 1E-6); assertFalse(testStatistic.pairedTTest(sample1, sample3, .001)); - assertTrue(testStatistic.pairedTTest(sample1, sample3, .002)); + assertTrue(testStatistic.pairedTTest(sample1, sample3, .002)); } } diff --git a/src/test/java/org/apache/commons/math/stat/inference/TestUtilsTest.java b/src/test/java/org/apache/commons/math/stat/inference/TestUtilsTest.java index ed3c9e274..7559e732d 100644 --- a/src/test/java/org/apache/commons/math/stat/inference/TestUtilsTest.java +++ b/src/test/java/org/apache/commons/math/stat/inference/TestUtilsTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -42,17 +42,17 @@ public class TestUtilsTest extends TestCase { } public void testChiSquare() throws Exception { - - // Target values computed using R version 1.8.1 - // Some assembly required ;-) + + // Target values computed using R version 1.8.1 + // Some assembly required ;-) // Use sum((obs - exp)^2/exp) for the chi-square statistic and // 1 - pchisq(sum((obs - exp)^2/exp), length(obs) - 1) for the p-value - + long[] observed = {10, 9, 11}; double[] expected = {10, 10, 10}; assertEquals("chi-square statistic", 0.2, TestUtils.chiSquare(expected, observed), 10E-12); assertEquals("chi-square p-value", 0.904837418036, TestUtils.chiSquareTest(expected, observed), 1E-10); - + long[] observed1 = { 500, 623, 72, 70, 31 }; double[] expected1 = { 485, 541, 82, 61, 37 }; assertEquals( "chi-square test statistic", 9.023307936427388, TestUtils.chiSquare(expected1, observed1), 1E-10); @@ -65,8 +65,8 @@ public class TestUtilsTest extends TestCase { fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + long[] tooShortObs = { 0 }; double[] tooShortEx = { 1 }; try { @@ -85,7 +85,7 @@ public class TestUtilsTest extends TestCase { } catch (IllegalArgumentException ex) { // expected } - + // 0 expected count expected[0] = 0; try { @@ -93,8 +93,8 @@ public class TestUtilsTest extends TestCase { fail("bad expected count, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + // negative observed count expected[0] = 1; observed[0] = -1; @@ -103,25 +103,25 @@ public class TestUtilsTest extends TestCase { fail("bad expected count, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + } public void testChiSquareIndependence() throws Exception { - - // Target values computed using R version 1.8.1 - + + // Target values computed using R version 1.8.1 + long[][] counts = { {40, 22, 43}, {91, 21, 28}, {60, 10, 22}}; assertEquals( "chi-square test statistic", 22.709027688, TestUtils.chiSquare(counts), 1E-9); assertEquals("chi-square p-value", 0.000144751460134, TestUtils.chiSquareTest(counts), 1E-9); assertTrue("chi-square test reject", TestUtils.chiSquareTest(counts, 0.0002)); - assertTrue("chi-square test accept", !TestUtils.chiSquareTest(counts, 0.0001)); - + assertTrue("chi-square test accept", !TestUtils.chiSquareTest(counts, 0.0001)); + long[][] counts2 = {{10, 15}, {30, 40}, {60, 90} }; assertEquals( "chi-square test statistic", 0.168965517241, TestUtils.chiSquare(counts2), 1E-9); assertEquals("chi-square p-value",0.918987499852, TestUtils.chiSquareTest(counts2), 1E-9); - assertTrue("chi-square test accept", !TestUtils.chiSquareTest(counts2, 0.1)); - + assertTrue("chi-square test accept", !TestUtils.chiSquareTest(counts2, 0.1)); + // ragged input array long[][] counts3 = { {40, 22, 43}, {91, 21, 28}, {60, 10}}; try { @@ -130,7 +130,7 @@ public class TestUtilsTest extends TestCase { } catch (IllegalArgumentException ex) { // expected } - + // insufficient data long[][] counts4 = {{40, 22, 43}}; try { @@ -138,15 +138,15 @@ public class TestUtilsTest extends TestCase { fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } long[][] counts5 = {{40}, {40}, {30}, {10}}; try { TestUtils.chiSquare(counts5); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } - + } + // negative counts long[][] counts6 = {{10, -2}, {30, 40}, {60, 90} }; try { @@ -154,20 +154,20 @@ public class TestUtilsTest extends TestCase { fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } - + } + // bad alpha try { TestUtils.chiSquareTest(counts, 0); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected - } + } } - + public void testChiSquareLargeTestStatistic() throws Exception { double[] exp = new double[] { - 3389119.5, 649136.6, 285745.4, 25357364.76, 11291189.78, 543628.0, + 3389119.5, 649136.6, 285745.4, 25357364.76, 11291189.78, 543628.0, 232921.0, 437665.75 }; @@ -175,26 +175,26 @@ public class TestUtilsTest extends TestCase { 2372383, 584222, 257170, 17750155, 7903832, 489265, 209628, 393899 }; org.apache.commons.math.stat.inference.ChiSquareTestImpl csti = - new org.apache.commons.math.stat.inference.ChiSquareTestImpl(); - double cst = csti.chiSquareTest(exp, obs); + new org.apache.commons.math.stat.inference.ChiSquareTestImpl(); + double cst = csti.chiSquareTest(exp, obs); assertEquals("chi-square p-value", 0.0, cst, 1E-3); - assertEquals( "chi-square test statistic", + assertEquals( "chi-square test statistic", 114875.90421929007, TestUtils.chiSquare(exp, obs), 1E-9); } - + /** Contingency table containing zeros - PR # 32531 */ public void testChiSquareZeroCount() throws Exception { - // Target values computed using R version 1.8.1 + // Target values computed using R version 1.8.1 long[][] counts = { {40, 0, 4}, {91, 1, 2}, {60, 2, 0}}; assertEquals( "chi-square test statistic", 9.67444662263, TestUtils.chiSquare(counts), 1E-9); assertEquals("chi-square p-value", 0.0462835770603, - TestUtils.chiSquareTest(counts), 1E-9); + TestUtils.chiSquareTest(counts), 1E-9); } - + private double[] tooShortObs = { 1.0 }; private double[] emptyObs = {}; - private SummaryStatistics emptyStats = new SummaryStatistics(); + private SummaryStatistics emptyStats = new SummaryStatistics(); public void testOneSampleT() throws Exception { double[] observed = @@ -236,7 +236,7 @@ public class TestUtilsTest extends TestCase { } catch (IllegalArgumentException ex) { // expected } - + try { TestUtils.t(mu, emptyStats); fail("arguments too short, IllegalArgumentException expected"); @@ -255,7 +255,7 @@ public class TestUtilsTest extends TestCase { fail("insufficient data to perform t test, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } + } try { TestUtils.t(mu, (SummaryStatistics) null); @@ -268,20 +268,20 @@ public class TestUtilsTest extends TestCase { fail("insufficient data to perform t test, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } + } } - + public void testOneSampleTTest() throws Exception { double[] oneSidedP = {2d, 0d, 6d, 6d, 3d, 3d, 2d, 3d, -6d, 6d, 6d, 6d, 3d, 0d, 1d, 1d, 0d, 2d, 3d, 3d }; - SummaryStatistics oneSidedPStats = new SummaryStatistics(); + SummaryStatistics oneSidedPStats = new SummaryStatistics(); for (int i = 0; i < oneSidedP.length; i++) { oneSidedPStats.addValue(oneSidedP[i]); } // Target comparison values computed using R version 1.8.1 (Linux version) - assertEquals("one sample t stat", 3.86485535541, + assertEquals("one sample t stat", 3.86485535541, TestUtils.t(0d, oneSidedP), 10E-10); - assertEquals("one sample t stat", 3.86485535541, + assertEquals("one sample t stat", 3.86485535541, TestUtils.t(0d, oneSidedPStats),1E-10); assertEquals("one sample p value", 0.000521637019637, TestUtils.tTest(0d, oneSidedP) / 2d, 10E-10); @@ -291,102 +291,102 @@ public class TestUtilsTest extends TestCase { assertTrue("one sample t-test reject", TestUtils.tTest(0d, oneSidedPStats, 0.01)); assertTrue("one sample t-test accept", !TestUtils.tTest(0d, oneSidedP, 0.0001)); assertTrue("one sample t-test accept", !TestUtils.tTest(0d, oneSidedPStats, 0.0001)); - + try { TestUtils.tTest(0d, oneSidedP, 95); fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { TestUtils.tTest(0d, oneSidedPStats, 95); fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + } - + public void testTwoSampleTHeterscedastic() throws Exception { double[] sample1 = { 7d, -4d, 18d, 17d, -3d, -5d, 1d, 10d, 11d, -2d }; double[] sample2 = { -1d, 12d, -1d, -3d, 3d, -5d, 5d, 2d, -11d, -1d, -3d }; - SummaryStatistics sampleStats1 = new SummaryStatistics(); + SummaryStatistics sampleStats1 = new SummaryStatistics(); for (int i = 0; i < sample1.length; i++) { sampleStats1.addValue(sample1[i]); } - SummaryStatistics sampleStats2 = new SummaryStatistics(); + SummaryStatistics sampleStats2 = new SummaryStatistics(); for (int i = 0; i < sample2.length; i++) { sampleStats2.addValue(sample2[i]); } - + // Target comparison values computed using R version 1.8.1 (Linux version) - assertEquals("two sample heteroscedastic t stat", 1.60371728768, + assertEquals("two sample heteroscedastic t stat", 1.60371728768, TestUtils.t(sample1, sample2), 1E-10); - assertEquals("two sample heteroscedastic t stat", 1.60371728768, + assertEquals("two sample heteroscedastic t stat", 1.60371728768, TestUtils.t(sampleStats1, sampleStats2), 1E-10); - assertEquals("two sample heteroscedastic p value", 0.128839369622, + assertEquals("two sample heteroscedastic p value", 0.128839369622, TestUtils.tTest(sample1, sample2), 1E-10); - assertEquals("two sample heteroscedastic p value", 0.128839369622, - TestUtils.tTest(sampleStats1, sampleStats2), 1E-10); - assertTrue("two sample heteroscedastic t-test reject", + assertEquals("two sample heteroscedastic p value", 0.128839369622, + TestUtils.tTest(sampleStats1, sampleStats2), 1E-10); + assertTrue("two sample heteroscedastic t-test reject", TestUtils.tTest(sample1, sample2, 0.2)); - assertTrue("two sample heteroscedastic t-test reject", + assertTrue("two sample heteroscedastic t-test reject", TestUtils.tTest(sampleStats1, sampleStats2, 0.2)); - assertTrue("two sample heteroscedastic t-test accept", + assertTrue("two sample heteroscedastic t-test accept", !TestUtils.tTest(sample1, sample2, 0.1)); - assertTrue("two sample heteroscedastic t-test accept", + assertTrue("two sample heteroscedastic t-test accept", !TestUtils.tTest(sampleStats1, sampleStats2, 0.1)); - + try { TestUtils.tTest(sample1, sample2, .95); fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { TestUtils.tTest(sampleStats1, sampleStats2, .95); fail("alpha out of range, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { - // expected - } - + // expected + } + try { TestUtils.tTest(sample1, tooShortObs, .01); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { TestUtils.tTest(sampleStats1, (SummaryStatistics) null, .01); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { TestUtils.tTest(sample1, tooShortObs); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { TestUtils.tTest(sampleStats1, (SummaryStatistics) null); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected - } - + } + try { TestUtils.t(sample1, tooShortObs); fail("insufficient data, IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected } - + try { TestUtils.t(sampleStats1, (SummaryStatistics) null); fail("insufficient data, IllegalArgumentException expected"); @@ -397,37 +397,37 @@ public class TestUtilsTest extends TestCase { public void testTwoSampleTHomoscedastic() throws Exception { double[] sample1 ={2, 4, 6, 8, 10, 97}; double[] sample2 = {4, 6, 8, 10, 16}; - SummaryStatistics sampleStats1 = new SummaryStatistics(); + SummaryStatistics sampleStats1 = new SummaryStatistics(); for (int i = 0; i < sample1.length; i++) { sampleStats1.addValue(sample1[i]); } - SummaryStatistics sampleStats2 = new SummaryStatistics(); + SummaryStatistics sampleStats2 = new SummaryStatistics(); for (int i = 0; i < sample2.length; i++) { sampleStats2.addValue(sample2[i]); } - + // Target comparison values computed using R version 1.8.1 (Linux version) - assertEquals("two sample homoscedastic t stat", 0.73096310086, + assertEquals("two sample homoscedastic t stat", 0.73096310086, TestUtils.homoscedasticT(sample1, sample2), 10E-11); - assertEquals("two sample homoscedastic p value", 0.4833963785, - TestUtils.homoscedasticTTest(sampleStats1, sampleStats2), 1E-10); - assertTrue("two sample homoscedastic t-test reject", + assertEquals("two sample homoscedastic p value", 0.4833963785, + TestUtils.homoscedasticTTest(sampleStats1, sampleStats2), 1E-10); + assertTrue("two sample homoscedastic t-test reject", TestUtils.homoscedasticTTest(sample1, sample2, 0.49)); - assertTrue("two sample homoscedastic t-test accept", + assertTrue("two sample homoscedastic t-test accept", !TestUtils.homoscedasticTTest(sample1, sample2, 0.48)); } - + public void testSmallSamples() throws Exception { double[] sample1 = {1d, 3d}; - double[] sample2 = {4d, 5d}; - + double[] sample2 = {4d, 5d}; + // Target values computed using R, version 1.8.1 (linux version) assertEquals(-2.2360679775, TestUtils.t(sample1, sample2), 1E-10); assertEquals(0.198727388935, TestUtils.tTest(sample1, sample2), 1E-10); } - + public void testPaired() throws Exception { double[] sample1 = {1d, 3d, 5d, 7d}; double[] sample2 = {0d, 6d, 11d, 2d}; @@ -438,28 +438,28 @@ public class TestUtilsTest extends TestCase { assertEquals(0.774544295819, TestUtils.pairedTTest(sample1, sample2), 1E-10); assertEquals(0.001208, TestUtils.pairedTTest(sample1, sample3), 1E-6); assertFalse(TestUtils.pairedTTest(sample1, sample3, .001)); - assertTrue(TestUtils.pairedTTest(sample1, sample3, .002)); + assertTrue(TestUtils.pairedTTest(sample1, sample3, .002)); } - + private double[] classA = {93.0, 103.0, 95.0, 101.0}; private double[] classB = {99.0, 92.0, 102.0, 100.0, 102.0}; private double[] classC = {110.0, 115.0, 111.0, 117.0, 128.0}; - + private List classes = new ArrayList(); private OneWayAnova oneWayAnova = new OneWayAnovaImpl(); - + public void testOneWayAnovaUtils() throws Exception { classes.add(classA); classes.add(classB); classes.add(classC); - assertEquals(oneWayAnova.anovaFValue(classes), + assertEquals(oneWayAnova.anovaFValue(classes), TestUtils.oneWayAnovaFValue(classes), 10E-12); - assertEquals(oneWayAnova.anovaPValue(classes), + assertEquals(oneWayAnova.anovaPValue(classes), TestUtils.oneWayAnovaPValue(classes), 10E-12); - assertEquals(oneWayAnova.anovaTest(classes, 0.01), - TestUtils.oneWayAnovaTest(classes, 0.01)); - } + assertEquals(oneWayAnova.anovaTest(classes, 0.01), + TestUtils.oneWayAnovaTest(classes, 0.01)); + } } diff --git a/src/test/java/org/apache/commons/math/stat/ranking/NaturalRankingTest.java b/src/test/java/org/apache/commons/math/stat/ranking/NaturalRankingTest.java index 331a288b1..987f989d8 100644 --- a/src/test/java/org/apache/commons/math/stat/ranking/NaturalRankingTest.java +++ b/src/test/java/org/apache/commons/math/stat/ranking/NaturalRankingTest.java @@ -24,7 +24,7 @@ import junit.framework.TestCase; /** * Test cases for NaturalRanking class - * + * * @since 2.0 * @version $Revision$ $Date$ */ diff --git a/src/test/java/org/apache/commons/math/stat/regression/GLSMultipleLinearRegressionTest.java b/src/test/java/org/apache/commons/math/stat/regression/GLSMultipleLinearRegressionTest.java index 700b0d3a3..11dd87955 100644 --- a/src/test/java/org/apache/commons/math/stat/regression/GLSMultipleLinearRegressionTest.java +++ b/src/test/java/org/apache/commons/math/stat/regression/GLSMultipleLinearRegressionTest.java @@ -45,7 +45,7 @@ public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs omega[5] = new double[]{0, 0, 0, 0, 0, 6.0}; super.setUp(); } - + @Test(expected=IllegalArgumentException.class) public void cannotAddXSampleData() { createRegression().newSampleData(new double[]{}, null, null); @@ -55,7 +55,7 @@ public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs public void cannotAddNullYSampleData() { createRegression().newSampleData(null, new double[][]{}, null); } - + @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch() { double[] y = new double[]{1.0, 2.0}; @@ -63,12 +63,12 @@ public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs x[0] = new double[]{1.0, 0}; createRegression().newSampleData(y, x, null); } - + @Test(expected=IllegalArgumentException.class) public void cannotAddNullCovarianceData() { createRegression().newSampleData(new double[]{}, new double[][]{}, null); } - + @Test(expected=IllegalArgumentException.class) public void notEnoughData() { double[] reducedY = new double[y.length - 1]; @@ -79,7 +79,7 @@ public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs System.arraycopy(omega, 0, reducedO, 0, reducedO.length); createRegression().newSampleData(reducedY, reducedX, reducedO); } - + @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataWithSampleSizeMismatch() { double[] y = new double[]{1.0, 2.0}; @@ -120,5 +120,5 @@ public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs protected int getSampleSize() { return y.length; } - + } diff --git a/src/test/java/org/apache/commons/math/stat/regression/MultipleLinearRegressionAbstractTest.java b/src/test/java/org/apache/commons/math/stat/regression/MultipleLinearRegressionAbstractTest.java index 24d3ad80d..4ff058b57 100644 --- a/src/test/java/org/apache/commons/math/stat/regression/MultipleLinearRegressionAbstractTest.java +++ b/src/test/java/org/apache/commons/math/stat/regression/MultipleLinearRegressionAbstractTest.java @@ -33,14 +33,14 @@ public abstract class MultipleLinearRegressionAbstractTest { } protected abstract MultipleLinearRegression createRegression(); - + protected abstract int getNumberOfRegressors(); - + protected abstract int getSampleSize(); @Test public void canEstimateRegressionParameters(){ - double[] beta = regression.estimateRegressionParameters(); + double[] beta = regression.estimateRegressionParameters(); assertEquals(getNumberOfRegressors(), beta.length); } @@ -49,7 +49,7 @@ public abstract class MultipleLinearRegressionAbstractTest { double[] e = regression.estimateResiduals(); assertEquals(getSampleSize(), e.length); } - + @Test public void canEstimateRegressionParametersVariance(){ double[][] variance = regression.estimateRegressionParametersVariance(); @@ -62,6 +62,6 @@ public abstract class MultipleLinearRegressionAbstractTest { double variance = regression.estimateRegressandVariance(); assertTrue(variance > 0.0); } - } + } } diff --git a/src/test/java/org/apache/commons/math/stat/regression/OLSMultipleLinearRegressionTest.java b/src/test/java/org/apache/commons/math/stat/regression/OLSMultipleLinearRegressionTest.java index bed07d434..b2bce924d 100644 --- a/src/test/java/org/apache/commons/math/stat/regression/OLSMultipleLinearRegressionTest.java +++ b/src/test/java/org/apache/commons/math/stat/regression/OLSMultipleLinearRegressionTest.java @@ -31,7 +31,7 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs private double[] y; private double[][] x; - + @Before @Override public void setUp(){ @@ -62,7 +62,7 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs protected int getSampleSize() { return y.length; } - + @Test(expected=IllegalArgumentException.class) public void cannotAddXSampleData() { createRegression().newSampleData(new double[]{}, null); @@ -72,7 +72,7 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs public void cannotAddNullYSampleData() { createRegression().newSampleData(null, new double[][]{}); } - + @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch() { double[] y = new double[]{1.0, 2.0}; @@ -80,11 +80,11 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs x[0] = new double[]{1.0, 0}; createRegression().newSampleData(y, x); } - + @Test public void testPerfectFit() { double[] betaHat = regression.estimateRegressionParameters(); - TestUtils.assertEquals(betaHat, + TestUtils.assertEquals(betaHat, new double[]{ 11.0, 1.0 / 2.0, 2.0 / 3.0, 3.0 / 4.0, 4.0 / 5.0, 5.0 / 6.0 }, 1e-14); double[] residuals = regression.estimateResiduals(); @@ -109,15 +109,15 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs errors.subtract(referenceVariance).getNorm(), 5.0e-16 * referenceVariance.getNorm()); } - - + + /** * Test Longley dataset against certified values provided by NIST. * Data Source: J. Longley (1967) "An Appraisal of Least Squares * Programs for the Electronic Computer from the Point of View of the User" * Journal of the American Statistical Association, vol. 62. September, * pp. 819-841. - * + * * Certified values (and data) are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */ @@ -143,23 +143,23 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; - + // Transform to Y and X required by interface int nobs = 16; int nvars = 6; - + // Estimate the model OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); model.newSampleData(design, nobs, nvars); - + // Check expected beta values from NIST double[] betaHat = model.estimateRegressionParameters(); - TestUtils.assertEquals(betaHat, + TestUtils.assertEquals(betaHat, new double[]{-3482258.63459582, 15.0618722713733, -0.358191792925910E-01,-2.02022980381683, -1.03322686717359,-0.511041056535807E-01, - 1829.15146461355}, 2E-8); // - + 1829.15146461355}, 2E-8); // + // Check expected residuals from R double[] residuals = model.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{ @@ -170,7 +170,7 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs -155.5499735953195,-85.6713080421283,341.9315139607727, -206.7578251937366}, 1E-8); - + // Check standard errors from NIST double[] errors = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(new double[] {890420.383607373, @@ -179,9 +179,9 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs 0.488399681651699, 0.214274163161675, 0.226073200069370, - 455.478499142212}, errors, 1E-6); + 455.478499142212}, errors, 1E-6); } - + /** * Test R Swiss fertility dataset against R. * Data Source: R datasets package @@ -248,7 +248,7 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs // Check expected beta values from R double[] betaHat = model.estimateRegressionParameters(); - TestUtils.assertEquals(betaHat, + TestUtils.assertEquals(betaHat, new double[]{91.05542390271397, -0.22064551045715, -0.26058239824328, @@ -274,30 +274,30 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs 5.4326230830188482,-7.2375578629692230,2.1671550814448222, 15.0147574652763112,4.8625103516321015,-7.1597256413907706, -0.4515205619767598,-10.2916870903837587,-15.7812984571900063}, - 1E-12); - + 1E-12); + // Check standard errors from R double[] errors = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(new double[] {6.94881329475087, 0.07360008972340, 0.27410957467466, 0.19454551679325, - 0.03726654773803}, errors, 1E-10); + 0.03726654773803}, errors, 1E-10); } - + /** * Test hat matrix computation - * + * * @throws Exception */ @Test public void testHat() throws Exception { - + /* - * This example is from "The Hat Matrix in Regression and ANOVA", - * David C. Hoaglin and Roy E. Welsch, + * This example is from "The Hat Matrix in Regression and ANOVA", + * David C. Hoaglin and Roy E. Welsch, * The American Statistician, Vol. 32, No. 1 (Feb., 1978), pp. 17-22. - * + * */ double[] design = new double[] { 11.14, .499, 11.1, @@ -311,16 +311,16 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs 11.02, .406, 10.5, 11.41, .467, 10.7 }; - + int nobs = 10; int nvars = 2; - + // Estimate the model OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); model.newSampleData(design, nobs, nvars); - + RealMatrix hat = model.calculateHat(); - + // Reference data is upper half of symmetric hat matrix double[] referenceData = new double[] { .418, -.002, .079, -.274, -.046, .181, .128, .222, .050, .242, @@ -334,24 +334,24 @@ public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbs .315, .148, .187 }; - + // Check against reference data and verify symmetry int k = 0; for (int i = 0; i < 10; i++) { for (int j = i; j < 10; j++) { assertEquals(referenceData[k], hat.getEntry(i, j), 10e-3); assertEquals(hat.getEntry(i, j), hat.getEntry(j, i), 10e-12); - k++; + k++; } } - - /* - * Verify that residuals computed using the hat matrix are close to + + /* + * Verify that residuals computed using the hat matrix are close to * what we get from direct computation, i.e. r = (I - H) y */ double[] residuals = model.estimateResiduals(); RealMatrix I = MatrixUtils.createRealIdentityMatrix(10); double[] hatResiduals = I.subtract(hat).operate(model.Y).getData(); - TestUtils.assertEquals(residuals, hatResiduals, 10e-12); + TestUtils.assertEquals(residuals, hatResiduals, 10e-12); } } diff --git a/src/test/java/org/apache/commons/math/stat/regression/SimpleRegressionTest.java b/src/test/java/org/apache/commons/math/stat/regression/SimpleRegressionTest.java index b71d36b15..5e3dbb1a9 100644 --- a/src/test/java/org/apache/commons/math/stat/regression/SimpleRegressionTest.java +++ b/src/test/java/org/apache/commons/math/stat/regression/SimpleRegressionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,39 +29,39 @@ import junit.framework.TestSuite; public final class SimpleRegressionTest extends TestCase { - /* - * NIST "Norris" refernce data set from + /* + * NIST "Norris" refernce data set from * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Norris.dat * Strangely, order is {y,x} */ - private double[][] data = { { 0.1, 0.2 }, {338.8, 337.4 }, {118.1, 118.2 }, - {888.0, 884.6 }, {9.2, 10.1 }, {228.1, 226.5 }, {668.5, 666.3 }, {998.5, 996.3 }, - {449.1, 448.6 }, {778.9, 777.0 }, {559.2, 558.2 }, {0.3, 0.4 }, {0.1, 0.6 }, {778.1, 775.5 }, - {668.8, 666.9 }, {339.3, 338.0 }, {448.9, 447.5 }, {10.8, 11.6 }, {557.7, 556.0 }, - {228.3, 228.1 }, {998.0, 995.8 }, {888.8, 887.6 }, {119.6, 120.2 }, {0.3, 0.3 }, - {0.6, 0.3 }, {557.6, 556.8 }, {339.3, 339.1 }, {888.0, 887.2 }, {998.5, 999.0 }, - {778.9, 779.0 }, {10.2, 11.1 }, {117.6, 118.3 }, {228.9, 229.2 }, {668.4, 669.1 }, + private double[][] data = { { 0.1, 0.2 }, {338.8, 337.4 }, {118.1, 118.2 }, + {888.0, 884.6 }, {9.2, 10.1 }, {228.1, 226.5 }, {668.5, 666.3 }, {998.5, 996.3 }, + {449.1, 448.6 }, {778.9, 777.0 }, {559.2, 558.2 }, {0.3, 0.4 }, {0.1, 0.6 }, {778.1, 775.5 }, + {668.8, 666.9 }, {339.3, 338.0 }, {448.9, 447.5 }, {10.8, 11.6 }, {557.7, 556.0 }, + {228.3, 228.1 }, {998.0, 995.8 }, {888.8, 887.6 }, {119.6, 120.2 }, {0.3, 0.3 }, + {0.6, 0.3 }, {557.6, 556.8 }, {339.3, 339.1 }, {888.0, 887.2 }, {998.5, 999.0 }, + {778.9, 779.0 }, {10.2, 11.1 }, {117.6, 118.3 }, {228.9, 229.2 }, {668.4, 669.1 }, {449.2, 448.9 }, {0.2, 0.5 } }; - /* - * Correlation example from + /* + * Correlation example from * http://www.xycoon.com/correlation.htm */ - private double[][] corrData = { { 101.0, 99.2 }, {100.1, 99.0 }, {100.0, 100.0 }, - {90.6, 111.6 }, {86.5, 122.2 }, {89.7, 117.6 }, {90.6, 121.1 }, {82.8, 136.0 }, - {70.1, 154.2 }, {65.4, 153.6 }, {61.3, 158.5 }, {62.5, 140.6 }, {63.6, 136.2 }, + private double[][] corrData = { { 101.0, 99.2 }, {100.1, 99.0 }, {100.0, 100.0 }, + {90.6, 111.6 }, {86.5, 122.2 }, {89.7, 117.6 }, {90.6, 121.1 }, {82.8, 136.0 }, + {70.1, 154.2 }, {65.4, 153.6 }, {61.3, 158.5 }, {62.5, 140.6 }, {63.6, 136.2 }, {52.6, 168.0 }, {59.7, 154.3 }, {59.5, 149.0 }, {61.3, 165.5 } }; /* * From Moore and Mcabe, "Introduction to the Practice of Statistics" - * Example 10.3 + * Example 10.3 */ private double[][] infData = { { 15.6, 5.2 }, {26.8, 6.1 }, {37.8, 8.7 }, {36.4, 8.5 }, {35.5, 8.8 }, {18.6, 4.9 }, {15.3, 4.5 }, {7.9, 2.5 }, {0.0, 1.1 } }; - + /* * Points to remove in the remove tests */ @@ -69,8 +69,8 @@ public final class SimpleRegressionTest extends TestCase { private double[][] removeMultiple = { infData[1], infData[2] }; private double removeX = infData[0][0]; private double removeY = infData[0][1]; - - + + /* * Data with bad linear fit */ @@ -93,7 +93,7 @@ public final class SimpleRegressionTest extends TestCase { for (int i = 0; i < data.length; i++) { regression.addData(data[i][1], data[i][0]); } - // Tests against certified values from + // Tests against certified values from // http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Norris.dat assertEquals("slope", 1.00211681802045, regression.getSlope(), 10E-12); assertEquals("slope std err", 0.429796848199937E-03, @@ -112,7 +112,7 @@ public final class SimpleRegressionTest extends TestCase { assertEquals("SSE", 26.6173985294224, regression.getSumSquaredErrors(),10E-9); // ------------ End certified data tests - + assertEquals( "predict(0)", -0.262323073774029, regression.predict(0), 10E-12); assertEquals("predict(1)", 1.00211681802045 - 0.262323073774029, @@ -164,7 +164,7 @@ public final class SimpleRegressionTest extends TestCase { regression.addData(1, 2); regression.addData(3, 3); - // All should be OK except MSE, s(b0), s(b1) which need one more df + // All should be OK except MSE, s(b0), s(b1) which need one more df assertTrue("interceptNaN", !Double.isNaN(regression.getIntercept())); assertTrue("slope NaN", !Double.isNaN(regression.getSlope())); assertTrue ("slope std err not NaN", Double.isNaN(regression.getSlopeStdErr())); @@ -207,8 +207,8 @@ public final class SimpleRegressionTest extends TestCase { assertEquals("std err intercept", 0.286036932, regression.getInterceptStdErr(),1E-8); assertEquals("significance", 4.596e-07, - regression.getSignificance(),1E-8); - assertEquals("slope conf interval half-width", 0.0270713794287, + regression.getSignificance(),1E-8); + assertEquals("slope conf interval half-width", 0.0270713794287, regression.getSlopeConfidenceInterval(),1E-8); // infData2 regression = new SimpleRegression(); @@ -218,21 +218,21 @@ public final class SimpleRegressionTest extends TestCase { assertEquals("std err intercept",4.17718672, regression.getInterceptStdErr(),1E-8); assertEquals("significance", 0.261829133982, - regression.getSignificance(),1E-11); - assertEquals("slope conf interval half-width", 2.97802204827, + regression.getSignificance(),1E-11); + assertEquals("slope conf interval half-width", 2.97802204827, regression.getSlopeConfidenceInterval(),1E-8); //------------- End R-verified tests ------------------------------- - + //FIXME: get a real example to test against with alpha = .01 assertTrue("tighter means wider", regression.getSlopeConfidenceInterval() < regression.getSlopeConfidenceInterval(0.01)); - + try { regression.getSlopeConfidenceInterval(1); fail("expecting IllegalArgumentException for alpha = 1"); } catch (IllegalArgumentException ex) { // ignored - } + } } @@ -253,9 +253,9 @@ public final class SimpleRegressionTest extends TestCase { for (int i = 0; i < n; i++) { regression.addData(- ((double) i) / (n - 1), i); } - + assertEquals(0.0, regression.getSignificance(), 1.0e-5); - assertTrue(regression.getSlope() < 0.0); + assertTrue(regression.getSlope() < 0.0); } public void testRandom() throws Exception { @@ -267,10 +267,10 @@ public final class SimpleRegressionTest extends TestCase { } assertTrue( 0.0 < regression.getSignificance() - && regression.getSignificance() < 1.0); + && regression.getSignificance() < 1.0); } - - + + // Jira MATH-85 = Bugzilla 39432 public void testSSENonNegative() { double[] y = { 8915.102, 8919.302, 8923.502 }; @@ -280,8 +280,8 @@ public final class SimpleRegressionTest extends TestCase { reg.addData(x[i], y[i]); } assertTrue(reg.getSumSquaredErrors() >= 0.0); - } - + } + // Test remove X,Y (single observation) public void testRemoveXY() throws Exception { // Create regression with inference data then remove to test @@ -295,12 +295,12 @@ public final class SimpleRegressionTest extends TestCase { assertEquals("std err intercept", 0.286036932, regression.getInterceptStdErr(),1E-8); assertEquals("significance", 4.596e-07, - regression.getSignificance(),1E-8); - assertEquals("slope conf interval half-width", 0.0270713794287, + regression.getSignificance(),1E-8); + assertEquals("slope conf interval half-width", 0.0270713794287, regression.getSlopeConfidenceInterval(),1E-8); } - - + + // Test remove single observation in array public void testRemoveSingle() throws Exception { // Create regression with inference data then remove to test @@ -314,11 +314,11 @@ public final class SimpleRegressionTest extends TestCase { assertEquals("std err intercept", 0.286036932, regression.getInterceptStdErr(),1E-8); assertEquals("significance", 4.596e-07, - regression.getSignificance(),1E-8); - assertEquals("slope conf interval half-width", 0.0270713794287, + regression.getSignificance(),1E-8); + assertEquals("slope conf interval half-width", 0.0270713794287, regression.getSlopeConfidenceInterval(),1E-8); } - + // Test remove multiple observations public void testRemoveMultiple() throws Exception { // Create regression with inference data then remove to test @@ -332,18 +332,18 @@ public final class SimpleRegressionTest extends TestCase { assertEquals("std err intercept", 0.286036932, regression.getInterceptStdErr(),1E-8); assertEquals("significance", 4.596e-07, - regression.getSignificance(),1E-8); - assertEquals("slope conf interval half-width", 0.0270713794287, + regression.getSignificance(),1E-8); + assertEquals("slope conf interval half-width", 0.0270713794287, regression.getSlopeConfidenceInterval(),1E-8); } - + // Remove observation when empty public void testRemoveObsFromEmpty() { SimpleRegression regression = new SimpleRegression(); regression.removeData(removeX, removeY); assertEquals(regression.getN(), 0); } - + // Remove single observation to empty public void testRemoveObsFromSingle() { SimpleRegression regression = new SimpleRegression(); @@ -351,7 +351,7 @@ public final class SimpleRegressionTest extends TestCase { regression.removeData(removeX, removeY); assertEquals(regression.getN(), 0); } - + // Remove multiple observations to empty public void testRemoveMultipleToEmpty() { SimpleRegression regression = new SimpleRegression(); @@ -359,7 +359,7 @@ public final class SimpleRegressionTest extends TestCase { regression.removeData(removeMultiple); assertEquals(regression.getN(), 0); } - + // Remove multiple observations past empty (i.e. size of array > n) public void testRemoveMultiplePastEmpty() { SimpleRegression regression = new SimpleRegression(); diff --git a/src/test/java/org/apache/commons/math/transform/FastCosineTransformerTest.java b/src/test/java/org/apache/commons/math/transform/FastCosineTransformerTest.java index c26cd7977..c39ddb43d 100644 --- a/src/test/java/org/apache/commons/math/transform/FastCosineTransformerTest.java +++ b/src/test/java/org/apache/commons/math/transform/FastCosineTransformerTest.java @@ -25,8 +25,8 @@ import junit.framework.TestCase; *

      * FCT algorithm is exact, the small tolerance number is used only * to account for round-off errors. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class FastCosineTransformerTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/transform/FastFourierTransformerTest.java b/src/test/java/org/apache/commons/math/transform/FastFourierTransformerTest.java index 6123ee662..35f986bd0 100644 --- a/src/test/java/org/apache/commons/math/transform/FastFourierTransformerTest.java +++ b/src/test/java/org/apache/commons/math/transform/FastFourierTransformerTest.java @@ -26,8 +26,8 @@ import junit.framework.TestCase; *

      * FFT algorithm is exact, the small tolerance number is used only * to account for round-off errors. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class FastFourierTransformerTest extends TestCase { @@ -77,7 +77,7 @@ public final class FastFourierTransformerTest extends TestCase { assertEquals(y2[i].getImaginary(), result[i].getImaginary(), tolerance); } } - + public void test2DData() { FastFourierTransformer transformer = new FastFourierTransformer(); double tolerance = 1E-12; @@ -90,14 +90,14 @@ public final class FastFourierTransformerTest extends TestCase { -1.5), new Complex(0, .5)}}; Complex[][] output = (Complex[][])transformer.mdfft(input, true); Complex[][] output2 = (Complex[][])transformer.mdfft(output, false); - + assertEquals(input.length, output.length); assertEquals(input.length, output2.length); assertEquals(input[0].length, output[0].length); assertEquals(input[0].length, output2[0].length); assertEquals(input[1].length, output[1].length); assertEquals(input[1].length, output2[1].length); - + for (int i = 0; i < input.length; i++) { for (int j = 0; j < input[0].length; j++) { assertEquals(input[i][j].getImaginary(), output2[i][j].getImaginary(), @@ -109,7 +109,7 @@ public final class FastFourierTransformerTest extends TestCase { } } } - + /** * Test of transformer for the sine function. */ diff --git a/src/test/java/org/apache/commons/math/transform/FastHadamardTransformerTest.java b/src/test/java/org/apache/commons/math/transform/FastHadamardTransformerTest.java index 84c362def..09ebed190 100644 --- a/src/test/java/org/apache/commons/math/transform/FastHadamardTransformerTest.java +++ b/src/test/java/org/apache/commons/math/transform/FastHadamardTransformerTest.java @@ -98,7 +98,7 @@ public final class FastHadamardTransformerTest extends TestCase { } } - + private void checkInverseDoubleTransform(int[]x, int[] y) { // Initiate the transformer FastHadamardTransformer transformer = new FastHadamardTransformer(); @@ -115,5 +115,5 @@ public final class FastHadamardTransformerTest extends TestCase { } } - + } diff --git a/src/test/java/org/apache/commons/math/transform/FastSineTransformerTest.java b/src/test/java/org/apache/commons/math/transform/FastSineTransformerTest.java index e62c0d416..61ceb95e0 100644 --- a/src/test/java/org/apache/commons/math/transform/FastSineTransformerTest.java +++ b/src/test/java/org/apache/commons/math/transform/FastSineTransformerTest.java @@ -25,8 +25,8 @@ import junit.framework.TestCase; *

      * FST algorithm is exact, the small tolerance number is used only * to account for round-off errors. - * - * @version $Revision$ $Date$ + * + * @version $Revision$ $Date$ */ public final class FastSineTransformerTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/util/ContinuedFractionTest.java b/src/test/java/org/apache/commons/math/util/ContinuedFractionTest.java index 3dab14fb6..3c5006cc5 100644 --- a/src/test/java/org/apache/commons/math/util/ContinuedFractionTest.java +++ b/src/test/java/org/apache/commons/math/util/ContinuedFractionTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -34,7 +34,7 @@ public class ContinuedFractionTest extends TestCase { public void testGoldenRatio(){ ContinuedFraction cf = new ContinuedFraction() { - + @Override public double getA(int n, double x) { return 1.0; @@ -45,7 +45,7 @@ public class ContinuedFractionTest extends TestCase { return 1.0; } }; - + try { double gr = cf.evaluate(0.0, 10e-9); assertEquals(1.61803399, gr, 10e-9); diff --git a/src/test/java/org/apache/commons/math/util/DefaultTransformerTest.java b/src/test/java/org/apache/commons/math/util/DefaultTransformerTest.java index 0f3b1c0ac..daa5b9b29 100644 --- a/src/test/java/org/apache/commons/math/util/DefaultTransformerTest.java +++ b/src/test/java/org/apache/commons/math/util/DefaultTransformerTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,7 @@ import org.apache.commons.math.TestUtils; */ public class DefaultTransformerTest extends TestCase { /** - * + * */ public void testTransformDouble() throws Exception { double expected = 1.0; @@ -37,9 +37,9 @@ public class DefaultTransformerTest extends TestCase { DefaultTransformer t = new DefaultTransformer(); assertEquals(expected, t.transform(input), 1.0e-4); } - + /** - * + * */ public void testTransformNull(){ DefaultTransformer t = new DefaultTransformer(); @@ -50,29 +50,29 @@ public class DefaultTransformerTest extends TestCase { // expected } } - + /** - * + * */ public void testTransformInteger() throws Exception { double expected = 1.0; Integer input = Integer.valueOf(1); DefaultTransformer t = new DefaultTransformer(); assertEquals(expected, t.transform(input), 1.0e-4); - } - + } + /** - * + * */ public void testTransformBigDecimal() throws Exception { double expected = 1.0; BigDecimal input = new BigDecimal("1.0"); DefaultTransformer t = new DefaultTransformer(); assertEquals(expected, t.transform(input), 1.0e-4); - } - + } + /** - * + * */ public void testTransformString() throws Exception { double expected = 1.0; @@ -80,9 +80,9 @@ public class DefaultTransformerTest extends TestCase { DefaultTransformer t = new DefaultTransformer(); assertEquals(expected, t.transform(input), 1.0e-4); } - + /** - * + * */ public void testTransformObject(){ Boolean input = Boolean.TRUE; diff --git a/src/test/java/org/apache/commons/math/util/DoubleArrayAbstractTest.java b/src/test/java/org/apache/commons/math/util/DoubleArrayAbstractTest.java index b054df7be..464625f5f 100644 --- a/src/test/java/org/apache/commons/math/util/DoubleArrayAbstractTest.java +++ b/src/test/java/org/apache/commons/math/util/DoubleArrayAbstractTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ import junit.framework.TestCase; /** * This class contains test cases for the ExpandableDoubleArray. - * + * * @version $Revision$ $Date$ */ public abstract class DoubleArrayAbstractTest extends TestCase { diff --git a/src/test/java/org/apache/commons/math/util/MathUtilsTest.java b/src/test/java/org/apache/commons/math/util/MathUtilsTest.java index 1486c9d1d..38d994ef2 100644 --- a/src/test/java/org/apache/commons/math/util/MathUtilsTest.java +++ b/src/test/java/org/apache/commons/math/util/MathUtilsTest.java @@ -311,7 +311,7 @@ public final class MathUtilsTest extends TestCase { assertTrue(MathUtils.compareTo(152.308, 152.32, .011) < 0); assertTrue(MathUtils.compareTo(152.33, 152.318, .011) > 0); } - + public void testCosh() { double x = 3.0; double expected = 10.06766; @@ -361,7 +361,7 @@ public final class MathUtilsTest extends TestCase { assertFalse(MathUtils.equals(153, 153.00000000000006, 1)); assertTrue(MathUtils.equals(153, 152.99999999999997, 1)); assertFalse(MathUtils.equals(153, 152.99999999999994, 1)); - + assertTrue(MathUtils.equals(-128, -127.99999999999999, 1)); assertFalse(MathUtils.equals(-128, -127.99999999999997, 1)); assertTrue(MathUtils.equals(-128, -128.00000000000003, 1)); @@ -378,7 +378,7 @@ public final class MathUtilsTest extends TestCase { assertFalse(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 100000)); } - + public void testArrayEquals() { assertFalse(MathUtils.equals(new double[] { 1d }, null)); assertFalse(MathUtils.equals(null, new double[] { 1d })); @@ -406,7 +406,7 @@ public final class MathUtilsTest extends TestCase { assertEquals(i + "! ", factorial(i), MathUtils.factorialDouble(i), Double.MIN_VALUE); assertEquals(i + "! ", Math.log(factorial(i)), MathUtils.factorialLog(i), 10E-12); } - + assertEquals("0", 1, MathUtils.factorial(0)); assertEquals("0", 1.0d, MathUtils.factorialDouble(0), 1E-14); assertEquals("0", 0.0d, MathUtils.factorialLog(0), 1E-14); @@ -529,7 +529,7 @@ public final class MathUtilsTest extends TestCase { assertFalse(MathUtils.hash(new double[] { 1d }) == MathUtils.hash(new double[] { 1d, 1d })); } - + /** * Make sure that permuted arrays do not hash to the same value. */ @@ -537,12 +537,12 @@ public final class MathUtilsTest extends TestCase { double[] original = new double[10]; double[] permuted = new double[10]; RandomDataImpl random = new RandomDataImpl(); - + // Generate 10 distinct random values for (int i = 0; i < 10; i++) { original[i] = random.nextUniform(i + 0.5, i + 0.75); } - + // Generate a random permutation, making sure it is not the identity boolean isIdentity = true; do { @@ -554,7 +554,7 @@ public final class MathUtilsTest extends TestCase { permuted[i] = original[permutation[i]]; } } while (isIdentity); - + // Verify that permuted array has different hash assertFalse(MathUtils.hash(original) == MathUtils.hash(permuted)); } @@ -627,7 +627,7 @@ public final class MathUtilsTest extends TestCase { } catch (ArithmeticException ex) { // expected } - + try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Integer.MIN_VALUE, 1<<20); @@ -796,53 +796,53 @@ public final class MathUtilsTest extends TestCase { } } } - + public void testNormalizeArray() { double[] testValues1 = new double[] {1, 1, 2}; TestUtils.assertEquals( new double[] {.25, .25, .5}, MathUtils.normalizeArray(testValues1, 1), Double.MIN_VALUE); - + double[] testValues2 = new double[] {-1, -1, 1}; TestUtils.assertEquals( new double[] {1, 1, -1}, MathUtils.normalizeArray(testValues2, 1), Double.MIN_VALUE); - + // Ignore NaNs double[] testValues3 = new double[] {-1, -1, Double.NaN, 1, Double.NaN}; TestUtils.assertEquals( new double[] {1, 1,Double.NaN, -1, Double.NaN}, MathUtils.normalizeArray(testValues3, 1), Double.MIN_VALUE); - + // Zero sum -> ArithmeticException double[] zeroSum = new double[] {-1, 1}; try { MathUtils.normalizeArray(zeroSum, 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} - + // Infinite elements -> ArithmeticException double[] hasInf = new double[] {1, 2, 1, Double.NEGATIVE_INFINITY}; try { MathUtils.normalizeArray(hasInf, 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} - + // Infinite target -> IllegalArgumentException try { MathUtils.normalizeArray(testValues1, Double.POSITIVE_INFINITY); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} - + // NaN target -> IllegalArgumentException try { MathUtils.normalizeArray(testValues1, Double.NaN); fail("expecting IllegalArgumentException"); - } catch (IllegalArgumentException ex) {} - + } catch (IllegalArgumentException ex) {} + } public void testRoundDouble() { @@ -1225,7 +1225,7 @@ public final class MathUtilsTest extends TestCase { assertEquals(bigOne, MathUtils.pow(twentyOne, 103)); assertEquals(bigOne, MathUtils.pow(twentyOne, 103l)); assertEquals(bigOne, MathUtils.pow(twentyOne, BigInteger.valueOf(103l))); - + } public void testL1DistanceDouble() { diff --git a/src/test/java/org/apache/commons/math/util/OpenIntToDoubleHashMapTest.java b/src/test/java/org/apache/commons/math/util/OpenIntToDoubleHashMapTest.java index e150ab99b..5c0c64178 100644 --- a/src/test/java/org/apache/commons/math/util/OpenIntToDoubleHashMapTest.java +++ b/src/test/java/org/apache/commons/math/util/OpenIntToDoubleHashMapTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -68,12 +68,12 @@ public class OpenIntToDoubleHashMapTest extends TestCase { } return map; } - + public void testPutAndGetWith0ExpectedSize() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(0); assertPutAndGet(map); } - + public void testPutAndGetWithExpectedSize() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(500); assertPutAndGet(map); @@ -122,7 +122,7 @@ public class OpenIntToDoubleHashMapTest extends TestCase { public void testGetAbsent() { Map generated = generateAbsent(); OpenIntToDoubleHashMap map = createFromJavaMap(); - + for (Map.Entry mapEntry : generated.entrySet()) assertTrue(Double.isNaN(map.get(mapEntry.getKey()))); } @@ -177,7 +177,7 @@ public class OpenIntToDoubleHashMapTest extends TestCase { OpenIntToDoubleHashMap map = createFromJavaMap(); int mapSize = map.size(); - + for (Map.Entry mapEntry : generated.entrySet()) { map.remove(mapEntry.getKey()); assertEquals(mapSize, map.size()); @@ -272,14 +272,14 @@ public class OpenIntToDoubleHashMapTest extends TestCase { map.put(key3, value1); assertEquals(value1, map.get(key3)); assertEquals(3, map.size()); - + map.remove(key2); double value2 = 2.0; map.put(key3, value2); assertEquals(value2, map.get(key3)); assertEquals(2, map.size()); } - + /** * Similar to testPutKeysWithCollisions() but exercises the codepaths in a slightly * different manner. @@ -293,7 +293,7 @@ public class OpenIntToDoubleHashMapTest extends TestCase { map.put(key2, value1); assertEquals(2, map.size()); assertEquals(value1, map.get(key2)); - + map.remove(key1); double value2 = 2.0; map.put(key2, value2); diff --git a/src/test/java/org/apache/commons/math/util/OpenIntToFieldTest.java b/src/test/java/org/apache/commons/math/util/OpenIntToFieldTest.java index 29d858dbc..f47fdcec3 100644 --- a/src/test/java/org/apache/commons/math/util/OpenIntToFieldTest.java +++ b/src/test/java/org/apache/commons/math/util/OpenIntToFieldTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -62,7 +62,7 @@ public class OpenIntToFieldTest extends TestCase { Random r = new Random(); double dd=0; for (int i = 0; i < 2000; ++i) - dd = r.nextDouble(); + dd = r.nextDouble(); try { map.put(r.nextInt(), new Fraction(dd)); } catch (FractionConversionException e) { @@ -78,12 +78,12 @@ public class OpenIntToFieldTest extends TestCase { } return map; } - + public void testPutAndGetWith0ExpectedSize() { OpenIntToFieldHashMap map = new OpenIntToFieldHashMap(field,0); assertPutAndGet(map); } - + public void testPutAndGetWithExpectedSize() { OpenIntToFieldHashMap map = new OpenIntToFieldHashMap(field,500); assertPutAndGet(map); @@ -132,7 +132,7 @@ public class OpenIntToFieldTest extends TestCase { public void testGetAbsent() { Map generated = generateAbsent(); OpenIntToFieldHashMap map = createFromJavaMap(field); - + for (Map.Entry mapEntry : generated.entrySet()) assertTrue(field.getZero().equals(map.get(mapEntry.getKey()))); } @@ -187,7 +187,7 @@ public class OpenIntToFieldTest extends TestCase { OpenIntToFieldHashMap map = createFromJavaMap(field); int mapSize = map.size(); - + for (Map.Entry mapEntry : generated.entrySet()) { map.remove(mapEntry.getKey()); assertEquals(mapSize, map.size()); @@ -282,14 +282,14 @@ public class OpenIntToFieldTest extends TestCase { map.put(key3, value1); assertEquals(value1, map.get(key3)); assertEquals(3, map.size()); - + map.remove(key2); Fraction value2 = new Fraction(2); map.put(key3, value2); assertEquals(value2, map.get(key3)); assertEquals(2, map.size()); } - + /** * Similar to testPutKeysWithCollisions() but exercises the codepaths in a slightly * different manner. @@ -303,7 +303,7 @@ public class OpenIntToFieldTest extends TestCase { map.put(key2, value1); assertEquals(2, map.size()); assertEquals(value1, map.get(key2)); - + map.remove(key1); Fraction value2 = new Fraction(2); map.put(key2, value2); diff --git a/src/test/java/org/apache/commons/math/util/ResizableDoubleArrayTest.java b/src/test/java/org/apache/commons/math/util/ResizableDoubleArrayTest.java index fda2d8fd0..b869028d5 100644 --- a/src/test/java/org/apache/commons/math/util/ResizableDoubleArrayTest.java +++ b/src/test/java/org/apache/commons/math/util/ResizableDoubleArrayTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,11 +21,11 @@ import org.apache.commons.math.random.RandomData; /** * This class contains test cases for the ResizableDoubleArray. - * + * * @version $Revision$ $Date$ */ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { - + public ResizableDoubleArrayTest(String name) { super( name ); } @@ -35,18 +35,18 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { da = null; ra = null; } - + @Override protected void setUp() throws Exception { da = new ResizableDoubleArray(); ra = new ResizableDoubleArray(); } - + public void testConstructors() { float defaultExpansionFactor = 2.0f; float defaultContractionCriteria = 2.5f; int defaultMode = ResizableDoubleArray.MULTIPLICATIVE_MODE; - + ResizableDoubleArray testDa = new ResizableDoubleArray(2); assertEquals(0, testDa.getNumElements()); assertEquals(2, testDa.getInternalLength()); @@ -59,88 +59,88 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { } catch (IllegalArgumentException ex) { // expected } - + testDa = new ResizableDoubleArray(2, 2.0f); assertEquals(0, testDa.getNumElements()); assertEquals(2, testDa.getInternalLength()); assertEquals(defaultExpansionFactor, testDa.getExpansionFactor(), 0); assertEquals(defaultContractionCriteria, testDa.getContractionCriteria(), 0); assertEquals(defaultMode, testDa.getExpansionMode()); - + try { da = new ResizableDoubleArray(2, 0.5f); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } - + testDa = new ResizableDoubleArray(2, 3.0f); assertEquals(3.0f, testDa.getExpansionFactor(), 0); assertEquals(3.5f, testDa.getContractionCriteria(), 0); - + testDa = new ResizableDoubleArray(2, 2.0f, 3.0f); assertEquals(0, testDa.getNumElements()); assertEquals(2, testDa.getInternalLength()); assertEquals(defaultExpansionFactor, testDa.getExpansionFactor(), 0); assertEquals(3.0f, testDa.getContractionCriteria(), 0); assertEquals(defaultMode, testDa.getExpansionMode()); - + try { da = new ResizableDoubleArray(2, 2.0f, 1.5f); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } - - testDa = new ResizableDoubleArray(2, 2.0f, 3.0f, + + testDa = new ResizableDoubleArray(2, 2.0f, 3.0f, ResizableDoubleArray.ADDITIVE_MODE); assertEquals(0, testDa.getNumElements()); assertEquals(2, testDa.getInternalLength()); assertEquals(defaultExpansionFactor, testDa.getExpansionFactor(), 0); assertEquals(3.0f, testDa.getContractionCriteria(), 0); - assertEquals(ResizableDoubleArray.ADDITIVE_MODE, + assertEquals(ResizableDoubleArray.ADDITIVE_MODE, testDa.getExpansionMode()); - + try { da = new ResizableDoubleArray(2, 2.0f, 2.5f, -1); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } - + // Copy constructor - testDa = new ResizableDoubleArray(2, 2.0f, 3.0f, + testDa = new ResizableDoubleArray(2, 2.0f, 3.0f, ResizableDoubleArray.ADDITIVE_MODE); testDa.addElement(2.0); testDa.addElement(3.2); ResizableDoubleArray copyDa = new ResizableDoubleArray(testDa); assertEquals(copyDa, testDa); - assertEquals(testDa, copyDa); + assertEquals(testDa, copyDa); } - - + + public void testSetElementArbitraryExpansion() { - - // MULTIPLICATIVE_MODE + + // MULTIPLICATIVE_MODE da.addElement(2.0); da.addElement(4.0); da.addElement(6.0); da.setElement(1, 3.0); - + // Expand the array arbitrarily to 1000 items da.setElement(1000, 3.4); - - assertEquals( "The number of elements should now be 1001, it isn't", + + assertEquals( "The number of elements should now be 1001, it isn't", da.getNumElements(), 1001); - + assertEquals( "Uninitialized Elements are default value of 0.0, index 766 wasn't", 0.0, da.getElement( 760 ), Double.MIN_VALUE ); - - assertEquals( "The 1000th index should be 3.4, it isn't", 3.4, da.getElement(1000), + + assertEquals( "The 1000th index should be 3.4, it isn't", 3.4, da.getElement(1000), Double.MIN_VALUE ); - assertEquals( "The 0th index should be 2.0, it isn't", 2.0, da.getElement(0), - Double.MIN_VALUE); - + assertEquals( "The 0th index should be 2.0, it isn't", 2.0, da.getElement(0), + Double.MIN_VALUE); + // Make sure numElements and expansion work correctly for expansion boundary cases da.clear(); da.addElement(2.0); @@ -157,24 +157,24 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { da.setElement(9, 10.0); assertEquals(11, ((ResizableDoubleArray) da).getInternalLength()); assertEquals(11, da.getNumElements()); - + try { da.setElement(-2, 3); fail("Expecting ArrayIndexOutOfBoundsException for negative index"); } catch (ArrayIndexOutOfBoundsException ex) { // expected } - + // ADDITIVE_MODE - - ResizableDoubleArray testDa = new ResizableDoubleArray(2, 2.0f, 3.0f, + + ResizableDoubleArray testDa = new ResizableDoubleArray(2, 2.0f, 3.0f, ResizableDoubleArray.ADDITIVE_MODE); assertEquals(2, testDa.getInternalLength()); testDa.addElement(1d); testDa.addElement(1d); assertEquals(2, testDa.getInternalLength()); testDa.addElement(1d); - assertEquals(4, testDa.getInternalLength()); + assertEquals(4, testDa.getInternalLength()); } @Override @@ -188,7 +188,7 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { @Override public void testAddElementRolling() { super.testAddElementRolling(); - + // MULTIPLICATIVE_MODE da.clear(); da.addElement(1); @@ -203,10 +203,10 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { da.addElementRolling(6); assertEquals(4, da.getElement(0), 0); assertEquals(5, da.getElement(1), 0); - assertEquals(6, da.getElement(2), 0); - + assertEquals(6, da.getElement(2), 0); + // ADDITIVE_MODE (x's are occupied storage locations, 0's are open) - ResizableDoubleArray testDa = new ResizableDoubleArray(2, 2.0f, 2.5f, + ResizableDoubleArray testDa = new ResizableDoubleArray(2, 2.0f, 2.5f, ResizableDoubleArray.ADDITIVE_MODE); assertEquals(2, testDa.getInternalLength()); testDa.addElement(1d); // x,0 @@ -214,27 +214,27 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { testDa.addElement(3d); // x,x,x,0 -- expanded assertEquals(1d, testDa.getElement(0), 0); assertEquals(2d, testDa.getElement(1), 0); - assertEquals(3d, testDa.getElement(2), 0); - assertEquals(4, testDa.getInternalLength()); // x,x,x,0 + assertEquals(3d, testDa.getElement(2), 0); + assertEquals(4, testDa.getInternalLength()); // x,x,x,0 assertEquals(3, testDa.getNumElements()); testDa.addElementRolling(4d); assertEquals(2d, testDa.getElement(0), 0); assertEquals(3d, testDa.getElement(1), 0); - assertEquals(4d, testDa.getElement(2), 0); + assertEquals(4d, testDa.getElement(2), 0); assertEquals(4, testDa.getInternalLength()); // 0,x,x,x assertEquals(3, testDa.getNumElements()); testDa.addElementRolling(5d); // 0,0,x,x,x,0 -- time to contract assertEquals(3d, testDa.getElement(0), 0); assertEquals(4d, testDa.getElement(1), 0); - assertEquals(5d, testDa.getElement(2), 0); - assertEquals(4, testDa.getInternalLength()); // contracted -- x,x,x,0 + assertEquals(5d, testDa.getElement(2), 0); + assertEquals(4, testDa.getInternalLength()); // contracted -- x,x,x,0 assertEquals(3, testDa.getNumElements()); try { testDa.getElement(4); fail("Expecting ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException ex) { // expected - } + } try { testDa.getElement(-1); fail("Expecting ArrayIndexOutOfBoundsException"); @@ -242,7 +242,7 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { // expected } } - + public void testSetNumberOfElements() { da.addElement( 1.0 ); da.addElement( 1.0 ); @@ -251,64 +251,64 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { da.addElement( 1.0 ); da.addElement( 1.0 ); assertEquals( "Number of elements should equal 6", da.getNumElements(), 6); - + ((ResizableDoubleArray) da).setNumElements( 3 ); assertEquals( "Number of elements should equal 3", da.getNumElements(), 3); - + try { ((ResizableDoubleArray) da).setNumElements( -3 ); fail( "Setting number of elements to negative should've thrown an exception"); } catch( IllegalArgumentException iae ) { } - + ((ResizableDoubleArray) da).setNumElements(1024); assertEquals( "Number of elements should now be 1024", da.getNumElements(), 1024); assertEquals( "Element 453 should be a default double", da.getElement( 453 ), 0.0, Double.MIN_VALUE); - + } - + public void testWithInitialCapacity() { - + ResizableDoubleArray eDA2 = new ResizableDoubleArray(2); assertEquals("Initial number of elements should be 0", 0, eDA2.getNumElements()); - + RandomData randomData = new RandomDataImpl(); int iterations = randomData.nextInt(100, 1000); - + for( int i = 0; i < iterations; i++) { eDA2.addElement( i ); } - + assertEquals("Number of elements should be equal to " + iterations, iterations, eDA2.getNumElements()); - + eDA2.addElement( 2.0 ); - + assertEquals("Number of elements should be equals to " + (iterations +1), iterations + 1 , eDA2.getNumElements() ); } - + public void testWithInitialCapacityAndExpansionFactor() { - + ResizableDoubleArray eDA3 = new ResizableDoubleArray(3, 3.0f, 3.5f); assertEquals("Initial number of elements should be 0", 0, eDA3.getNumElements() ); - + RandomData randomData = new RandomDataImpl(); int iterations = randomData.nextInt(100, 3000); - + for( int i = 0; i < iterations; i++) { eDA3.addElement( i ); } - + assertEquals("Number of elements should be equal to " + iterations, iterations,eDA3.getNumElements()); - + eDA3.addElement( 2.0 ); - + assertEquals("Number of elements should be equals to " + (iterations +1), iterations +1, eDA3.getNumElements() ); - + assertEquals("Expansion factor should equal 3.0", 3.0f, eDA3.getExpansionFactor(), Double.MIN_VALUE); } - + public void testDiscard() { da.addElement(2.0); da.addElement(2.0); @@ -322,7 +322,7 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { da.addElement(2.0); da.addElement(2.0); assertEquals( "Number of elements should be 11", 11, da.getNumElements()); - + ((ResizableDoubleArray)da).discardFrontElements(5); assertEquals( "Number of elements should be 6", 6, da.getNumElements()); @@ -334,7 +334,7 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { ((ResizableDoubleArray)da).discardMostRecentElements(2); assertEquals( "Number of elements should be 8", 8, da.getNumElements()); - + try { ((ResizableDoubleArray)da).discardFrontElements(-1); fail( "Trying to discard a negative number of element is not allowed"); @@ -362,7 +362,7 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { } public void testSubstitute() { - + da.addElement(2.0); da.addElement(2.0); da.addElement(2.0); @@ -375,7 +375,7 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { da.addElement(2.0); da.addElement(2.0); assertEquals( "Number of elements should be 11", 11, da.getNumElements()); - + ((ResizableDoubleArray)da).substituteMostRecentElement(24); assertEquals( "Number of elements should be 11", 11, da.getNumElements()); @@ -391,11 +391,11 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { assertEquals( "Number of elements should be 1", 1, da.getNumElements()); } - + public void testMutators() { ((ResizableDoubleArray)da).setContractionCriteria(10f); assertEquals(10f, ((ResizableDoubleArray)da).getContractionCriteria(), 0); - ((ResizableDoubleArray)da).setExpansionFactor(8f); + ((ResizableDoubleArray)da).setExpansionFactor(8f); assertEquals(8f, ((ResizableDoubleArray)da).getExpansionFactor(), 0); try { ((ResizableDoubleArray)da).setExpansionFactor(11f); // greater than contractionCriteria @@ -405,7 +405,7 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { } ((ResizableDoubleArray)da).setExpansionMode( ResizableDoubleArray.ADDITIVE_MODE); - assertEquals(ResizableDoubleArray.ADDITIVE_MODE, + assertEquals(ResizableDoubleArray.ADDITIVE_MODE, ((ResizableDoubleArray)da).getExpansionMode()); try { ((ResizableDoubleArray)da).setExpansionMode(-1); @@ -414,25 +414,25 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { // expected } } - + public void testEqualsAndHashCode() throws Exception { - + // Wrong type ResizableDoubleArray first = new ResizableDoubleArray(); Double other = new Double(2); assertFalse(first.equals(other)); - + // Null other = null; assertFalse(first.equals(other)); - + // Reflexive assertTrue(first.equals(first)); - + // Argumentless constructor ResizableDoubleArray second = new ResizableDoubleArray(); verifyEquality(first, second); - + // Equals iff same data, same properties ResizableDoubleArray third = new ResizableDoubleArray(3, 2.0f, 2.0f); verifyInequality(third, first); @@ -447,7 +447,7 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { fourth.addElement(4.2); fourth.addElement(4.3); verifyEquality(third, fourth); - + // expand fourth.addElement(4.4); verifyInequality(third, fourth); @@ -460,47 +460,47 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest { fourth.addElementRolling(4.5); third.addElementRolling(4.5); verifyEquality(third, fourth); - + // discard third.discardFrontElements(1); verifyInequality(third, fourth); fourth.discardFrontElements(1); verifyEquality(third, fourth); - + // discard recent third.discardMostRecentElements(2); fourth.discardMostRecentElements(2); verifyEquality(third, fourth); - + // wrong order third.addElement(18); fourth.addElement(17); third.addElement(17); fourth.addElement(18); verifyInequality(third, fourth); - + // copy ResizableDoubleArray.copy(fourth, fifth); verifyEquality(fourth, fifth); - + // Copy constructor verifyEquality(fourth, new ResizableDoubleArray(fourth)); - + // Instance copy - verifyEquality(fourth, fourth.copy()); - + verifyEquality(fourth, fourth.copy()); + } - + private void verifyEquality(ResizableDoubleArray a, ResizableDoubleArray b) { assertTrue(b.equals(a)); assertTrue(a.equals(b)); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(a.hashCode(), b.hashCode()); } - + private void verifyInequality(ResizableDoubleArray a, ResizableDoubleArray b) { assertFalse(b.equals(a)); assertFalse(a.equals(b)); assertFalse(a.hashCode() == b.hashCode()); } - + } diff --git a/src/test/java/org/apache/commons/math/util/TestBean.java b/src/test/java/org/apache/commons/math/util/TestBean.java index 071c347e4..2b7fa6c31 100644 --- a/src/test/java/org/apache/commons/math/util/TestBean.java +++ b/src/test/java/org/apache/commons/math/util/TestBean.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,42 +28,42 @@ public class TestBean { private String y = "1.0"; /** - * + * */ public Double getX() { return x; } /** - * + * */ public String getY() { return y; } /** - * + * */ public void setX(Double double1) { x = double1; } /** - * + * */ public void setY(String string) { y = string; } - + /** - * + * */ public Double getZ() { throw new MathRuntimeException("?"); } /** - * + * */ public void setZ(Double double1) { } diff --git a/src/test/java/org/apache/commons/math/util/TransformerMapTest.java b/src/test/java/org/apache/commons/math/util/TransformerMapTest.java index 94d7ee9fa..0c498aa1d 100644 --- a/src/test/java/org/apache/commons/math/util/TransformerMapTest.java +++ b/src/test/java/org/apache/commons/math/util/TransformerMapTest.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,18 +26,18 @@ import junit.framework.TestCase; */ public class TransformerMapTest extends TestCase { /** - * + * */ public void testPutTransformer(){ NumberTransformer expected = new DefaultTransformer(); - + TransformerMap map = new TransformerMap(); map.putTransformer(TransformerMapTest.class, expected); assertEquals(expected, map.getTransformer(TransformerMapTest.class)); } - + /** - * + * */ public void testContainsClass(){ NumberTransformer expected = new DefaultTransformer(); @@ -45,9 +45,9 @@ public class TransformerMapTest extends TestCase { map.putTransformer(TransformerMapTest.class, expected); assertTrue(map.containsClass(TransformerMapTest.class)); } - + /** - * + * */ public void testContainsTransformer(){ NumberTransformer expected = new DefaultTransformer(); @@ -57,11 +57,11 @@ public class TransformerMapTest extends TestCase { } /** - * + * */ public void testRemoveTransformer(){ NumberTransformer expected = new DefaultTransformer(); - + TransformerMap map = new TransformerMap(); map.putTransformer(TransformerMapTest.class, expected); assertTrue(map.containsClass(TransformerMapTest.class)); @@ -72,20 +72,20 @@ public class TransformerMapTest extends TestCase { } /** - * + * */ public void testClear(){ NumberTransformer expected = new DefaultTransformer(); - + TransformerMap map = new TransformerMap(); map.putTransformer(TransformerMapTest.class, expected); assertTrue(map.containsClass(TransformerMapTest.class)); map.clear(); assertFalse(map.containsClass(TransformerMapTest.class)); } - + /** - * + * */ public void testClasses(){ NumberTransformer expected = new DefaultTransformer(); @@ -93,9 +93,9 @@ public class TransformerMapTest extends TestCase { map.putTransformer(TransformerMapTest.class, expected); assertTrue(map.classes().contains(TransformerMapTest.class)); } - + /** - * + * */ public void testTransformers(){ NumberTransformer expected = new DefaultTransformer();