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

The following are Jave code examples for showing how to use createIllegalArgumentException() of the org.apache.commons.math.MathRuntimeException class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: astor   File: Covariance.java   View Source Code Vote up 6 votes
/**
 * Computes the covariance between the two arrays.
 *
 * <p>Array lengths must match and the common length must be at least 2.</p>
 *
 * @param xArray first data array
 * @param yArray second data array
 * @param biasCorrected if true, returned value will be bias-corrected
 * @return returns the covariance for the two arrays
 * @throws  IllegalArgumentException if the arrays lengths do not match or
 * there is insufficient data
 */
public double covariance(final double[] xArray, final double[] yArray, boolean biasCorrected)
    throws IllegalArgumentException {
    Mean mean = new Mean();
    double result = 0d;
    int length = xArray.length;
    if(length == yArray.length && length > 1) {
        double xMean = mean.evaluate(xArray);
        double yMean = mean.evaluate(yArray);
        for (int i = 0; i < length; i++) {
            double xDev = xArray[i] - xMean;
            double yDev = yArray[i] - yMean;
            result += (xDev * yDev - result) / (i + 1);
        }
    }
    else {
        throw MathRuntimeException.createIllegalArgumentException(
           "arrays must have the same length and both must have at " +
           "least two elements. xArray has size {0}, yArray has {1} elements",
                length, yArray.length);
    }
    return biasCorrected ? result * ((double) length / (double)(length - 1)) : result;
}
 
Example 2
Project: astor   File: ResizableDoubleArray.java   View Source Code Vote up 6 votes
/**
 * 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
 *         the expansionCriteria.
 */
protected void checkContractExpand(float contraction, float expansion) {

    if (contraction < expansion) {
        throw MathRuntimeException.createIllegalArgumentException(
                "contraction criteria ({0}) smaller than the expansion factor ({1}).  This would " +
                "lead to a never ending loop of expansion and contraction as a newly expanded " +
                "internal storage array would immediately satisfy the criteria for contraction",
                contraction, expansion);
    }

    if (contraction <= 1.0) {
        throw MathRuntimeException.createIllegalArgumentException(
                "contraction criteria smaller than one ({0}).  This would lead to a never ending " +
                "loop of expansion and contraction as an internal storage array length equal " +
                "to the number of elements would satisfy the contraction criteria.",
                contraction);
    }

    if (expansion <= 1.0) {
        throw MathRuntimeException.createIllegalArgumentException(
                "expansion factor smaller than one ({0})",
                expansion);
    }
}
 
Example 3
Project: astor   File: BigMatrixImpl.java   View Source Code Vote up 6 votes
/**
 * Create a new BigMatrix using <code>d</code> as the underlying
 * data array.
 * <p>Since the underlying array will hold <code>BigDecimal</code>
 * instances, it will be created.</p>
 *
 * @param d data for new matrix
 * @throws IllegalArgumentException if <code>d</code> is not rectangular
 *  (not all rows have the same length) or empty
 * @throws NullPointerException if <code>d</code> is null
 */
public BigMatrixImpl(double[][] d) {
    final int nRows = d.length;
    if (nRows == 0) {
        throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one row");
    }

    final int nCols = d[0].length;
    if (nCols == 0) {
        throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one column");
    }
    for (int row = 1; row < nRows; row++) {
        if (d[row].length != nCols) {
            throw MathRuntimeException.createIllegalArgumentException(
                  "some rows have length {0} while others have length {1}",
                  nCols, d[row].length);
        }
    }
    this.copyIn(d);
    lu = null;
}
 
Example 4
Project: astor   File: Fraction.java   View Source Code Vote up 5 votes
/**
 * <p>Divide the value of this fraction by another.</p>
 *
 * @param fraction  the fraction to divide by, must not be <code>null</code>
 * @return a <code>Fraction</code> instance with the resulting values
 * @throws IllegalArgumentException if the fraction is <code>null</code>
 * @throws ArithmeticException if the fraction to divide by is zero
 * @throws ArithmeticException if the resulting numerator or denominator exceeds
 *  <code>Integer.MAX_VALUE</code>
 */
public Fraction divide(Fraction fraction) {
    if (fraction == null) {
        throw MathRuntimeException.createIllegalArgumentException(NULL_FRACTION);
    }
    if (fraction.numerator == 0) {
        throw MathRuntimeException.createArithmeticException(
                "the fraction to divide by must not be zero: {0}/{1}",
                fraction.numerator, fraction.denominator);
    }
    return multiply(fraction.reciprocal());
}
 
Example 5
Project: astor   File: TrapezoidIntegrator.java   View Source Code Vote up 5 votes
/** {@inheritDoc} */
@Override
protected void verifyIterationCount() throws IllegalArgumentException {
    super.verifyIterationCount();
    // at most 64 bisection refinements
    if (maximalIterationCount > 64) {
        throw MathRuntimeException.createIllegalArgumentException(
                "invalid iteration limits: min={0}, max={1}",
                0, 64);
    }
}
 
Example 6
Project: astor   File: RecursiveLayoutRealMatrix.java   View Source Code Vote up 5 votes
/**
 * Create a new dense matrix copying entries from recursive layout data.
 * <p>The input array <em>must</em> already be in recursive layout.</p>
 * @param rows  the number of rows in the new matrix
 * @param columns  the number of columns in the new matrix
 * @param data data for new matrix, in recursive layout
 * @param copyArray if true, the input array will be copied, otherwise
 * it will be referenced
 *
 * @exception IllegalArgumentException if <code>data</code> size is
 * inconsistent with matrix size
 * @see #toRecursiveLayout(double[][])
 * @see #RecursiveLayoutRealMatrix(double[][])
 */
public RecursiveLayoutRealMatrix(final int rows, final int columns,
                                 final double[] data, final boolean copyArray)
    throws IllegalArgumentException {

    super(rows, columns);
    this.rows    = rows;
    this.columns = columns;

    // compute optimal layout
    tileNumber      = tilesNumber(rows, columns);
    tileSizeRows    = tileSize(rows, tileNumber);
    tileSizeColumns = tileSize(columns, tileNumber);

    // create storage array
    final int expectedLength = tileNumber * tileNumber * tileSizeRows * tileSizeColumns;
    if (data.length != expectedLength) {
        throw MathRuntimeException.createIllegalArgumentException(
                "wrong array size (got {0}, expected {1})",
                data.length, expectedLength);
    }

    if (copyArray) {
        // allocate storage array
        this.data = data.clone();
    } else {
        // reference existing array
        this.data = data;
    }

}
 
Example 7
Project: astor   File: FDistributionImpl.java   View Source Code Vote up 5 votes
/**
 * Modify the denominator degrees of freedom.
 * @param degreesOfFreedom the new denominator degrees of freedom.
 * @throws IllegalArgumentException if <code>degreesOfFreedom</code> is not
 *         positive.
 */
public void setDenominatorDegreesOfFreedom(double degreesOfFreedom) {
    if (degreesOfFreedom <= 0.0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "degrees of freedom must be positive ({0})",
              degreesOfFreedom);
    }
    this.denominatorDegreesOfFreedom = degreesOfFreedom;
}
 
Example 8
Project: astor   File: PearsonsCorrelation.java   View Source Code Vote up 5 votes
/**
 * Create a PearsonsCorrelation from a {@link Covariance}.  The correlation
 * matrix is computed by scaling the Covariance's covariance matrix.
 * The Covariance instance must have been created from a data matrix with
 * columns representing variable values.
 *
 * @param covariance Covariance instance
 */
public PearsonsCorrelation(Covariance covariance) {
    RealMatrix covarianceMatrix = covariance.getCovarianceMatrix();
    if (covarianceMatrix == null) {
        throw MathRuntimeException.createIllegalArgumentException("covariance matrix is null");
    }
    nObs = covariance.getN();
    correlationMatrix = covarianceToCorrelation(covarianceMatrix);
}
 
Example 9
Project: astor   File: MatrixUtils.java   View Source Code Vote up 5 votes
/**
 * Creates a row {@link FieldMatrix} using the data from the input
 * array. 
 * 
 * @param <T> the type of the field elements
 * @param rowData the input row data
 * @return a 1 x rowData.length FieldMatrix
 * @throws IllegalArgumentException if <code>rowData</code> is empty
 * @throws NullPointerException if <code>rowData</code>is null
 */
public static <T extends FieldElement<T>> FieldMatrix<T>
    createRowFieldMatrix(final T[] rowData) {
    final int nCols = rowData.length;
    if (nCols == 0) {
        throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one column"); 
    }
    final FieldMatrix<T> m = createFieldMatrix(rowData[0].getField(), 1, nCols);
    for (int i = 0; i < nCols; ++i) {
        m.setEntry(0, i, rowData[i]);
    }
    return m;
}
 
Example 10
Project: astor   File: PearsonsCorrelation.java   View Source Code Vote up 5 votes
/**
 * Throws IllegalArgumentException of the matrix does not have at least
 * two columns and two rows
 *
 * @param matrix matrix to check for sufficiency
 */
private void checkSufficientData(final RealMatrix matrix) {
    int nRows = matrix.getRowDimension();
    int nCols = matrix.getColumnDimension();
    if (nRows < 2 || nCols < 2) {
        throw MathRuntimeException.createIllegalArgumentException(
                "insufficient data: only {0} rows and {1} columns.",
                nRows, nCols);
    }
}
 
Example 11
Project: astor   File: PascalDistributionImpl.java   View Source Code Vote up 5 votes
/**
 * Change the probability of success for this distribution.
 * @param p the new probability of success
 * @throws IllegalArgumentException if <code>p</code> is not a valid
 *         probability.
 */
public void setProbabilityOfSuccess(double p) {
    if (p < 0.0 || p > 1.0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "{0} out of [{1}, {2}] range", p, 0.0, 1.0);
    }
    probabilityOfSuccess = p;
}
 
Example 12
Project: astor   File: MathUtils.java   View Source Code Vote up 5 votes
/**
 * Raise a BigInteger to an int power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, int e)
    throws IllegalArgumentException {

    if (e < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            "cannot raise an integral value to a negative power ({0}^{1})",
            k, e);
    }

    return k.pow(e);

}
 
Example 13
Project: astor   File: MatrixUtils.java   View Source Code Vote up 5 votes
/**
 * Check if matrices are subtraction compatible
 * @param left left hand side matrix
 * @param right right hand side matrix
 * @exception IllegalArgumentException if matrices are not subtraction compatible
 */
public static void checkSubtractionCompatible(final AnyMatrix left, final AnyMatrix right)
    throws IllegalArgumentException {
    if ((left.getRowDimension()    != right.getRowDimension()) ||
        (left.getColumnDimension() != right.getColumnDimension())) {
        throw MathRuntimeException.createIllegalArgumentException(
                "{0}x{1} and {2}x{3} matrices are not subtraction compatible",
                left.getRowDimension(), left.getColumnDimension(),
                right.getRowDimension(), right.getColumnDimension());
    }
}
 
Example 14
Project: astor   File: GammaDistributionImpl.java   View Source Code Vote up 5 votes
/**
 * Modify the shape parameter, alpha.
 * @param alpha the new shape parameter.
 * @throws IllegalArgumentException if <code>alpha</code> is not positive.
 */
public void setAlpha(double alpha) {
    if (alpha <= 0.0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "alpha must be positive ({0})",
              alpha);
    }
    this.alpha = alpha;
}
 
Example 15
Project: astor   File: FastCosineTransformer.java   View Source Code Vote up 4 votes
/**
 * Perform the FCT algorithm (including inverse).
 *
 * @param f the real data array to be transformed
 * @return the real transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
protected double[] fct(double f[])
    throws IllegalArgumentException {

    double A, B, C, F1, x[], F[] = new double[f.length];

    int N = f.length - 1;
    if (!FastFourierTransformer.isPowerOf2(N)) {
        throw MathRuntimeException.createIllegalArgumentException(
                "{0} is not a power of 2 plus one",
                f.length);
    }
    if (N == 1) {       // trivial case
        F[0] = 0.5 * (f[0] + f[1]);
        F[1] = 0.5 * (f[0] - f[1]);
        return F;
    }

    // construct a new array and perform FFT on it
    x = new double[N];
    x[0] = 0.5 * (f[0] + f[N]);
    x[N >> 1] = f[N >> 1];
    F1 = 0.5 * (f[0] - f[N]);   // temporary variable for F[1]
    for (int i = 1; i < (N >> 1); i++) {
        A = 0.5 * (f[i] + f[N-i]);
        B = Math.sin(i * Math.PI / N) * (f[i] - f[N-i]);
        C = Math.cos(i * Math.PI / N) * (f[i] - f[N-i]);
        x[i] = A - B;
        x[N-i] = A + B;
        F1 += C;
    }
    FastFourierTransformer transformer = new FastFourierTransformer();
    Complex y[] = transformer.transform(x);

    // reconstruct the FCT result for the original array
    F[0] = y[0].getReal();
    F[1] = F1;
    for (int i = 1; i < (N >> 1); i++) {
        F[2*i] = y[i].getReal();
        F[2*i+1] = F[2*i-1] - y[i].getImaginary();
    }
    F[N] = y[N >> 1].getReal();

    return F;
}
 
Example 16
Project: astor   File: BigMatrixImpl.java   View Source Code Vote up 4 votes
/**
 * Replace the submatrix starting at <code>row, column</code> using data in
 * the input <code>subMatrix</code> array. Indexes are 0-based.
 * <p>
 * Example:<br>
 * Starting with <pre>
 * 1  2  3  4
 * 5  6  7  8
 * 9  0  1  2
 * </pre>
 * and <code>subMatrix = {{3, 4} {5,6}}</code>, invoking
 * <code>setSubMatrix(subMatrix,1,1))</code> will result in <pre>
 * 1  2  3  4
 * 5  3  4  8
 * 9  5  6  2
 * </pre></p>
 *
 * @param subMatrix  array containing the submatrix replacement data
 * @param row  row coordinate of the top, left element to be replaced
 * @param column  column coordinate of the top, left element to be replaced
 * @throws MatrixIndexException  if subMatrix does not fit into this
 *    matrix from element in (row, column)
 * @throws IllegalArgumentException if <code>subMatrix</code> is not rectangular
 *  (not all rows have the same length) or empty
 * @throws NullPointerException if <code>subMatrix</code> is null
 * @since 1.1
 */
public void setSubMatrix(BigDecimal[][] subMatrix, int row, int column)
throws MatrixIndexException {

    final int nRows = subMatrix.length;
    if (nRows == 0) {
        throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one row");
    }

    final int nCols = subMatrix[0].length;
    if (nCols == 0) {
        throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one column");
    }

    for (int r = 1; r < nRows; r++) {
        if (subMatrix[r].length != nCols) {
            throw MathRuntimeException.createIllegalArgumentException(
                  "some rows have length {0} while others have length {1}",
                  nCols, subMatrix[r].length);
        }
    }

    if (data == null) {
        if (row > 0) {
            throw MathRuntimeException.createIllegalStateException(
                    "first {0} rows are not initialized yet",
                    row);
        }
        if (column > 0) {
            throw MathRuntimeException.createIllegalStateException(
                    "first {0} columns are not initialized yet",
                    column);
        }
        data = new BigDecimal[nRows][nCols];
        System.arraycopy(subMatrix, 0, data, 0, subMatrix.length);
    } else {
        MatrixUtils.checkRowIndex(this, row);
        MatrixUtils.checkColumnIndex(this, column);
        MatrixUtils.checkRowIndex(this, nRows + row - 1);
        MatrixUtils.checkColumnIndex(this, nCols + column - 1);
    }
    for (int i = 0; i < nRows; i++) {
        System.arraycopy(subMatrix[i], 0, data[row + i], column, nCols);
    }

    lu = null;

}
 
Example 17
Project: astor   File: RandomDataImpl.java   View Source Code Vote up 4 votes
/**
 * Generates an integer array of length <code>k</code> whose entries are
 * selected randomly, without repetition, from the integers
 * <code>0 through n-1</code> (inclusive).
 * <p>
 * Generated arrays represent permutations of <code>n</code> taken
 * <code>k</code> at a time.
 * </p>
 * <p>
 * <strong>Preconditions:</strong>
 * <ul>
 * <li> <code>k <= n</code></li>
 * <li> <code>n > 0</code></li>
 * </ul>
 * If the preconditions are not met, an IllegalArgumentException is thrown.
 * </p>
 * <p>
 * Uses a 2-cycle permutation shuffle. The shuffling process is described <a
 * href="http://www.maths.abdn.ac.uk/~igc/tch/mx4002/notes/node83.html">
 * here</a>.
 * </p>
 *
 * @param n
 *            domain of the permutation (must be positive)
 * @param k
 *            size of the permutation (must satisfy 0 < k <= n).
 * @return the random permutation as an int array
 */
public int[] nextPermutation(int n, int k) {
    if (k > n) {
        throw MathRuntimeException.createIllegalArgumentException(
              "permutation k ({0}) exceeds n ({1})", k, n);
    }
    if (k == 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "permutation k ({0}) must be positive", k);
    }

    int[] index = getNatural(n);
    shuffle(index, n - k);
    int[] result = new int[k];
    for (int i = 0; i < k; i++) {
        result[i] = index[n - i - 1];
    }

    return result;
}
 
Example 18
Project: astor   File: SimpleRegression.java   View Source Code Vote up 3 votes
/**
 * Returns the half-width of a (100-100*alpha)% confidence interval for
 * the slope estimate.
 * <p>
 * The (100-100*alpha)% confidence interval is </p>
 * <p>
 * <code>(getSlope() - getSlopeConfidenceInterval(),
 * getSlope() + getSlopeConfidenceInterval())</code></p>
 * <p>
 * To request, for example, a 99% confidence interval, use
 * <code>alpha = .01</code></p>
 * <p>
 * <strong>Usage Note</strong>:<br>
 * The validity of this statistic depends on the assumption that the
 * observations included in the model are drawn from a
 * <a href="http://mathworld.wolfram.com/BivariateNormalDistribution.html">
 * Bivariate Normal Distribution</a>.</p>
 * <p>
 * <strong> Preconditions:</strong><ul>
 * <li>If there are fewer that <strong>three</strong> observations in the
 * model, or if there is no variation in x, this returns
 * <code>Double.NaN</code>.
 * </li>
 * <li><code>(0 < alpha < 1)</code>; otherwise an
 * <code>IllegalArgumentException</code> is thrown.
 * </li></ul></p>
 *
 * @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.
 */
public double getSlopeConfidenceInterval(double alpha)
    throws MathException {
    if (alpha >= 1 || alpha <= 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "out of bounds significance level {0}, must be between {1} and {2}",
              alpha, 0.0, 1.0);
    }
    return getSlopeStdErr() *
        distribution.inverseCumulativeProbability(1d - alpha / 2d);
}
 
Example 19
Project: astor   File: Variance.java   View Source Code Vote up 3 votes
/**
 * Returns the variance of the entries in the input array, or
 * <code>Double.NaN</code> if the array is empty.
 * <p>
 * See {@link Variance} for details on the computing algorithm.</p>
 * <p>
 * Returns 0 for a single-value (i.e. length = 1) sample.</p>
 * <p>
 * Throws <code>IllegalArgumentException</code> if the array is null.</p>
 * <p>
 * Does not change the internal state of the statistic.</p>
 *
 * @param values the input array
 * @return the variance of the values or Double.NaN if length = 0
 * @throws IllegalArgumentException if the array is null
 */
@Override
public double evaluate(final double[] values) {
    if (values == null) {
        throw MathRuntimeException.createIllegalArgumentException("input values array is null");
    }
    return evaluate(values, 0, values.length);
}
 
Example 20
Project: astor   File: AbstractStorelessUnivariateStatistic.java   View Source Code Vote up 3 votes
/**
 * This default implementation just calls {@link #increment} in a loop over
 * the input array.   
 * <p>
 * Throws IllegalArgumentException if the input values array is null.</p>
 * 
 * @param values values to add
 * @throws IllegalArgumentException if values is null
 * @see org.apache.commons.math.stat.descriptive.StorelessUnivariateStatistic#incrementAll(double[])
 */
public void incrementAll(double[] values) {
    if (values == null) {
        throw MathRuntimeException.createIllegalArgumentException("input values array is null");
    }
    incrementAll(values, 0, values.length);
}