org.apache.commons.math.exception.util.LocalizedFormats Java Examples

The following examples show how to use org.apache.commons.math.exception.util.LocalizedFormats. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: 1_MathUtils.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the natural logarithm of n!.
 * <p>
 * <Strong>Preconditions</strong>:
 * <ul>
 * <li> <code>n >= 0</code> (otherwise
 * <code>IllegalArgumentException</code> is thrown)</li>
 * </ul></p>
 *
 * @param n argument
 * @return <code>n!</code>
 * @throws IllegalArgumentException if preconditions are not met.
 */
public static double factorialLog(final int n) {
    if (n < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.FACTORIAL_NEGATIVE_PARAMETER,
              n);
    }
    if (n < 21) {
        return FastMath.log(factorial(n));
    }
    double logSum = 0;
    for (int i = 2; i <= n; i++) {
        logSum += FastMath.log(i);
    }
    return logSum;
}
 
Example #2
Source File: DefaultTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param o  the object that gets transformed.
 * @return a double primitive representation of the Object o.
 * @throws MathException if it cannot successfully be transformed.
 * @throws NullArgumentException if is {@code null}.
 * @see <a href="http://commons.apache.org/collections/api-release/org/apache/commons/collections/Transformer.html"/>
 */
public double transform(Object o) throws MathException {
    if (o == null) {
        throw new NullArgumentException(LocalizedFormats.OBJECT_TRANSFORMATION);
    }

    if (o instanceof Number) {
        return ((Number)o).doubleValue();
    }

    try {
        return Double.valueOf(o.toString()).doubleValue();
    } catch (NumberFormatException e) {
        throw new MathException(e,
                                LocalizedFormats.CANNOT_TRANSFORM_TO_DOUBLE, e.getMessage());
    }
}
 
Example #3
Source File: MatrixUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if submatrix ranges indices are valid.
 * Rows and columns are indicated counting from 0 to n-1.
 *
 * @param m Matrix.
 * @param selectedRows Array of row indices.
 * @param selectedColumns Array of column indices.
 * @throws NullArgumentException if {@code selectedRows} or
 * {@code selectedColumns} are {@code null}.
 * @throws NoDataException if the row or column selections are empty (zero
 * length).
 * @throws OutOfRangeException if row or column selections are not valid.
 */
public static void checkSubMatrixIndex(final AnyMatrix m,
                                       final int[] selectedRows,
                                       final int[] selectedColumns) {
    if (selectedRows == null) {
        throw new NullArgumentException();
    }
    if (selectedColumns == null) {
        throw new NullArgumentException();
    }
    if (selectedRows.length == 0) {
        throw new NoDataException(LocalizedFormats.EMPTY_SELECTED_ROW_INDEX_ARRAY);
    }
    if (selectedColumns.length == 0) {
        throw new NoDataException(LocalizedFormats.EMPTY_SELECTED_COLUMN_INDEX_ARRAY);
    }

    for (final int row : selectedRows) {
        checkRowIndex(m, row);
    }
    for (final int column : selectedColumns) {
        checkColumnIndex(m, column);
    }
}
 
Example #4
Source File: Fraction.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Multiplies the value of this fraction by another, returning the
 * result in reduced form.</p>
 *
 * @param fraction  the fraction to multiply by, must not be {@code null}
 * @return a {@code Fraction} instance with the resulting values
 * @throws NullArgumentException if the fraction is {@code null}
 * @throws MathArithmeticException if the resulting numerator or denominator exceeds
 *  {@code Integer.MAX_VALUE}
 */
public Fraction multiply(Fraction fraction) {
    if (fraction == null) {
        throw new NullArgumentException(LocalizedFormats.FRACTION);
    }
    if (numerator == 0 || fraction.numerator == 0) {
        return ZERO;
    }
    // knuth 4.5.1
    // make sure we don't overflow unless the result *must* overflow.
    int d1 = MathUtils.gcd(numerator, fraction.denominator);
    int d2 = MathUtils.gcd(fraction.numerator, denominator);
    return getReducedFraction
    (MathUtils.mulAndCheck(numerator/d1, fraction.numerator/d2),
            MathUtils.mulAndCheck(denominator/d2, fraction.denominator/d1));
}
 
Example #5
Source File: Cardumen_0053_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise an int to a long 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 int pow(final int k, long e)
    throws IllegalArgumentException {

    if (e < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    int result = 1;
    int k2p    = k;
    while (e != 0) {
        if ((e & 0x1) != 0) {
            result *= k2p;
        }
        k2p *= k2p;
        e = e >> 1;
    }

    return result;

}
 
Example #6
Source File: Cardumen_0053_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a long 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, long e)
    throws IllegalArgumentException {

    if (e < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (e != 0) {
        if ((e & 0x1) != 0) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e >> 1;
    }

    return result;

}
 
Example #7
Source File: Cardumen_00174_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger 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, BigInteger e)
    throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example #8
Source File: JGenProg2017_0025_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Advance iterator one step further.
 * @exception ConcurrentModificationException if the map is modified during iteration
 * @exception NoSuchElementException if there is no element left in the map
 */
public void advance()
    throws ConcurrentModificationException, NoSuchElementException {

    if (referenceCount != count) {
        throw MathRuntimeException.createConcurrentModificationException(LocalizedFormats.MAP_MODIFIED_WHILE_ITERATING);
    }

    // advance on step
    current = next;

    // prepare next step
    try {
        while (states[++next] != FULL) {
            // nothing to do
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        next = -2;
        if (current < 0) {
            throw MathRuntimeException.createNoSuchElementException(LocalizedFormats.ITERATOR_EXHAUSTED);
        }
    }

}
 
Example #9
Source File: jKali_0026_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Advance iterator one step further.
 * @exception ConcurrentModificationException if the map is modified during iteration
 * @exception NoSuchElementException if there is no element left in the map
 */
public void advance()
    throws ConcurrentModificationException, NoSuchElementException {

    if (referenceCount != count) {
        throw MathRuntimeException.createConcurrentModificationException(LocalizedFormats.MAP_MODIFIED_WHILE_ITERATING);
    }

    // advance on step
    current = next;

    // prepare next step
    try {
        while (states[++next] != FULL) {
            // nothing to do
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        next = -2;
        if (current < 0) {
            throw MathRuntimeException.createNoSuchElementException(LocalizedFormats.ITERATOR_EXHAUSTED);
        }
    }

}
 
Example #10
Source File: AbstractLeastSquaresOptimizer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Update the residuals array and cost function value.
 * @exception FunctionEvaluationException if the function cannot be evaluated
 * or its dimension doesn't match problem dimension or maximal number of
 * of evaluations is exceeded
 */
protected void updateResidualsAndCost() throws FunctionEvaluationException {
    objective = computeObjectiveValue(point);
    if (objective.length != rows) {
        throw new FunctionEvaluationException(point, LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE,
                                              objective.length, rows);
    }

    final double[] targetValues = getTargetRef();
    final double[] residualsWeights = getWeightRef();

    cost = 0;
    int index = 0;
    for (int i = 0; i < rows; i++) {
        final double residual = targetValues[i] - objective[i];
        weightedResiduals[i]= residual*FastMath.sqrt(residualsWeights[i]);
        cost += residualsWeights[i] * residual * residual;
        index += cols;
    }
    cost = FastMath.sqrt(cost);
}
 
Example #11
Source File: Cardumen_0053_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger 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, BigInteger e)
    throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example #12
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sample the given univariate real function on the given interval.
 * <p>
 * The interval is divided equally into N sections and sample points
 * are taken from min to max-(max-min)/N. Usually f(x) is periodic
 * such that f(min) = f(max) (note max is not sampled), but we don't
 * require that.</p>
 *
 * @param f the function to be sampled
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param n the number of sample points
 * @return the samples array
 * @throws MathUserException if function cannot be evaluated at some point
 * @throws IllegalArgumentException if any parameters are invalid
 */
public static double[] sample(UnivariateRealFunction f, double min, double max, int n)
    throws MathUserException, IllegalArgumentException {

    if (n <= 0) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NOT_POSITIVE_NUMBER_OF_SAMPLES,
                n);
    }
    verifyInterval(min, max);

    double s[] = new double[n];
    double h = (max - min) / n;
    for (int i = 0; i < n; i++) {
        s[i] = f.value(min + i * h);
    }
    return s;
}
 
Example #13
Source File: Frequency.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds 1 to the frequency count for v.
 * <p>
 * If other objects have already been added to this Frequency, v must
 * be comparable to those that have already been added.
 * </p>
 *
 * @param v the value to add.
 * @throws IllegalArgumentException if <code>v</code> is not comparable with previous entries
 */
public void addValue(Comparable<?> v){
    Comparable<?> obj = v;
    if (v instanceof Integer) {
       obj = Long.valueOf(((Integer) v).longValue());
    }
    try {
        Long count = freqTable.get(obj);
        if (count == null) {
            freqTable.put(obj, Long.valueOf(1));
        } else {
            freqTable.put(obj, Long.valueOf(count.longValue() + 1));
        }
    } catch (ClassCastException ex) {
        //TreeMap will throw ClassCastException if v is not comparable
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.INSTANCES_NOT_COMPARABLE_TO_EXISTING_VALUES,
              v.getClass().getName());
    }
}
 
Example #14
Source File: Cardumen_00267_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise an int to a long 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 int pow(final int k, long e)
    throws IllegalArgumentException {

    if (e < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    int result = 1;
    int k2p    = k;
    while (e != 0) {
        if ((e & 0x1) != 0) {
            result *= k2p;
        }
        k2p *= k2p;
        e = e >> 1;
    }

    return result;

}
 
Example #15
Source File: MatrixUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if submatrix ranges indices are valid.
 * Rows and columns are indicated counting from 0 to {@code n - 1}.
 *
 * @param m Matrix.
 * @param startRow Initial row index.
 * @param endRow Final row index.
 * @param startColumn Initial column index.
 * @param endColumn Final column index.
 * @throws OutOfRangeException if the indices are invalid.
 * @throws NumberIsTooSmallException if {@code endRow < startRow} or
 * {@code endColumn < startColumn}.
 */
public static void checkSubMatrixIndex(final AnyMatrix m,
                                       final int startRow, final int endRow,
                                       final int startColumn, final int endColumn) {
    checkRowIndex(m, startRow);
    checkRowIndex(m, endRow);
    if (endRow < startRow) {
        throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW,
                                            endRow, startRow, false);
    }

    checkColumnIndex(m, startColumn);
    checkColumnIndex(m, endColumn);
    if (endColumn < startColumn) {
        throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_COLUMN_AFTER_FINAL_COLUMN,
                                            endColumn, startColumn, false);
    }


}
 
Example #16
Source File: Arja_00126_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Advance iterator one step further.
 * @exception ConcurrentModificationException if the map is modified during iteration
 * @exception NoSuchElementException if there is no element left in the map
 */
public void advance()
    throws ConcurrentModificationException, NoSuchElementException {

    if (referenceCount != count) {
        throw MathRuntimeException.createConcurrentModificationException(LocalizedFormats.MAP_MODIFIED_WHILE_ITERATING);
    }

    // advance on step
    current = next;

    // prepare next step
    try {
        while (states[++next] != FULL) {
            // nothing to do
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        next = -2;
        if (current < 0) {
            throw MathRuntimeException.createNoSuchElementException(LocalizedFormats.ITERATOR_EXHAUSTED);
        }
    }

}
 
Example #17
Source File: Cardumen_00224_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a long 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, long e)
    throws IllegalArgumentException {

    if (e < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (e != 0) {
        if ((e & 0x1) != 0) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e >> 1;
    }

    return result;

}
 
Example #18
Source File: AbstractFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void copySubMatrix(int[] selectedRows, int[] selectedColumns, T[][] destination)
    throws MatrixIndexException, IllegalArgumentException {

    // safety checks
    checkSubMatrixIndex(selectedRows, selectedColumns);
    if ((destination.length < selectedRows.length) ||
        (destination[0].length < selectedColumns.length)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.DIMENSIONS_MISMATCH_2x2,
                destination.length, destination[0].length,
                selectedRows.length, selectedColumns.length);
    }

    // copy entries
    for (int i = 0; i < selectedRows.length; i++) {
        final T[] destinationI = destination[i];
        for (int j = 0; j < selectedColumns.length; j++) {
            destinationI[j] = getEntry(selectedRows[i], selectedColumns[j]);
        }
    }

}
 
Example #19
Source File: AbstractFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if submatrix ranges indices are valid.
 * Rows and columns are indicated counting from 0 to n-1.
 *
 * @param startRow Initial row index.
 * @param endRow Final row index.
 * @param startColumn Initial column index.
 * @param endColumn Final column index.
 * @throws OutOfRangeException if the indices are not valid.
 * @throws NumberIsTooSmallException if {@code endRow < startRow} or
 * {@code endColumn < startColumn}.
 */
protected void checkSubMatrixIndex(final int startRow, final int endRow,
                                   final int startColumn, final int endColumn) {
    checkRowIndex(startRow);
    checkRowIndex(endRow);
    if (endRow < startRow) {
        throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW,
                                            endRow, startRow, true);
    }

    checkColumnIndex(startColumn);
    checkColumnIndex(endColumn);
    if (endColumn < startColumn) {
        throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_COLUMN_AFTER_FINAL_COLUMN,
                                            endColumn, startColumn, true);
    }
}
 
Example #20
Source File: ResizableDoubleArray.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 <code>i</code> is negative.
 */
public synchronized void setNumElements(int i) {

    // If index is negative thrown an error
    if (i < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.INDEX_NOT_POSITIVE,
                i);
    }

    // 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);
    }

    // Set the new number of elements to new value
    numElements = i;
}
 
Example #21
Source File: DescriptiveStatistics.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the implementation to be used by {@link #getPercentile(double)}.
 * The supplied <code>UnivariateStatistic</code> must provide a
 * <code>setQuantile(double)</code> method; otherwise
 * <code>IllegalArgumentException</code> is thrown.
 *
 * @param percentileImpl the percentileImpl to set
 * @throws IllegalArgumentException if the supplied implementation does not
 *  provide a <code>setQuantile</code> method
 * @since 1.2
 */
public synchronized void setPercentileImpl(
        UnivariateStatistic percentileImpl) {
    try {
        percentileImpl.getClass().getMethod(SET_QUANTILE_METHOD_NAME,
                new Class[] {Double.TYPE}).invoke(percentileImpl,
                        new Object[] {Double.valueOf(50.0d)});
    } catch (NoSuchMethodException e1) {
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.PERCENTILE_IMPLEMENTATION_UNSUPPORTED_METHOD,
              percentileImpl.getClass().getName(), SET_QUANTILE_METHOD_NAME);
    } catch (IllegalAccessException e2) {
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.PERCENTILE_IMPLEMENTATION_CANNOT_ACCESS_METHOD,
              SET_QUANTILE_METHOD_NAME, percentileImpl.getClass().getName());
    } catch (InvocationTargetException e3) {
        throw MathRuntimeException.createIllegalArgumentException(e3.getCause());
    }
    this.percentileImpl = percentileImpl;
}
 
Example #22
Source File: AbstractUnivariateStatistic.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method is used by <code>evaluate(double[], int, int)</code> methods
 * to verify that the input parameters designate a subarray of positive length.
 * <p>
 * <ul>
 * <li>returns <code>true</code> iff the parameters designate a subarray of
 * non-negative length</li>
 * <li>throws <code>IllegalArgumentException</code> if the array is null or
 * or the indices are invalid</li>
 * <li>returns <code>false</li> if the array is non-null, but
 * <code>length</code> is 0 unless <code>allowEmpty</code> is <code>true</code>
 * </ul></p>
 *
 * @param values the input array
 * @param begin index of the first array element to include
 * @param length the number of elements to include
 * @param allowEmpty if <code>true</code> then zero length arrays are allowed
 * @return true if the parameters are valid
 * @throws IllegalArgumentException if the indices are invalid or the array is null
 * @since 3.0
 */
protected boolean test(final double[] values, final int begin, final int length, final boolean allowEmpty){

    if (values == null) {
        throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY);
    }

    if (begin < 0) {
        throw new NotPositiveException(LocalizedFormats.START_POSITION, begin);
    }

    if (length < 0) {
        throw new NotPositiveException(LocalizedFormats.LENGTH, length);
    }

    if (begin + length > values.length) {
        throw new NumberIsTooLargeException(LocalizedFormats.SUBARRAY_ENDS_AFTER_ARRAY_END,
                                            begin + length, values.length, true);
    }

    if (length == 0 && !allowEmpty) {
        return false;
    }

    return true;

}
 
Example #23
Source File: Cardumen_00267_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Check binomial preconditions.
 * @param n the size of the set
 * @param k the size of the subsets to be counted
 * @exception IllegalArgumentException if preconditions are not met.
 */
private static void checkBinomial(final int n, final int k)
    throws IllegalArgumentException {
    if (n < k) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.BINOMIAL_INVALID_PARAMETERS_ORDER,
            n, k);
    }
    if (n < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.BINOMIAL_NEGATIVE_PARAMETER,
              n);
    }
}
 
Example #24
Source File: SummaryStatistics.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Throws IllegalStateException if n > 0.
 */
private void checkEmpty() {
    if (n > 0) {
        throw MathRuntimeException.createIllegalStateException(
                LocalizedFormats.VALUES_ADDED_BEFORE_CONFIGURING_STATISTIC,
                n);
    }
}
 
Example #25
Source File: GeometricMean.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Throws IllegalStateException if n > 0.
 */
private void checkEmpty() {
    if (getN() > 0) {
        throw MathRuntimeException.createIllegalStateException(
                LocalizedFormats.VALUES_ADDED_BEFORE_CONFIGURING_STATISTIC,
                getN());
    }
}
 
Example #26
Source File: AbstractRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check if an index is valid.
 * @param index index to check
 * @exception MatrixIndexException if index is not valid
 */
protected void checkIndex(final int index)
    throws MatrixIndexException {
    if (index < 0 || index >= getDimension()) {
        throw new MatrixIndexException(LocalizedFormats.INDEX_OUT_OF_RANGE,
                                       index, 0, getDimension() - 1);
    }
}
 
Example #27
Source File: StatUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the sum of the (signed) differences between corresponding elements of the
 * input arrays -- i.e., sum(sample1[i] - sample2[i]).
 *
 * @param sample1  the first array
 * @param sample2  the second array
 * @return sum of paired differences
 * @throws DimensionMismatchException if the arrays do not have the same
 * (positive) length.
 * @throws NoDataException if the sample arrays are empty.
 */
public static double sumDifference(final double[] sample1, final double[] sample2) {
    int n = sample1.length;
    if (n != sample2.length) {
        throw new DimensionMismatchException(n, sample2.length);
    }
    if (n <= 0) {
        throw new NoDataException(LocalizedFormats.INSUFFICIENT_DIMENSION);
    }
    double result = 0;
    for (int i = 0; i < n; i++) {
        result += sample1[i] - sample2[i];
    }
    return result;
}
 
Example #28
Source File: Cardumen_00120_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Normalizes an array to make it sum to a specified value.
 * Returns the result of the transformation <pre>
 *    x |-> x * normalizedSum / sum
 * </pre>
 * applied to each non-NaN element x of the input array, where sum is the
 * sum of the non-NaN entries in the input array.</p>
 *
 * <p>Throws IllegalArgumentException if <code>normalizedSum</code> is infinite
 * or NaN and ArithmeticException if the input array contains any infinite elements
 * or sums to 0</p>
 *
 * <p>Ignores (i.e., copies unchanged to the output array) NaNs in the input array.</p>
 *
 * @param values input array to be normalized
 * @param normalizedSum target sum for the normalized array
 * @return normalized array
 * @throws ArithmeticException if the input array contains infinite elements or sums to zero
 * @throws IllegalArgumentException if the target sum is infinite or NaN
 * @since 2.1
 */
public static double[] normalizeArray(double[] values, double normalizedSum)
  throws ArithmeticException, IllegalArgumentException {
    if (Double.isInfinite(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NORMALIZE_INFINITE);
    }
    if (Double.isNaN(normalizedSum)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NORMALIZE_NAN);
    }
    double sum = 0d;
    final int len = values.length;
    double[] out = new double[len];
    for (int i = 0; i < len; i++) {
        if (Double.isInfinite(values[i])) {
            throw MathRuntimeException.createArithmeticException(
                    LocalizedFormats.INFINITE_ARRAY_ELEMENT, values[i], i);
        }
        if (!Double.isNaN(values[i])) {
            sum += values[i];
        }
    }
    if (sum == 0) {
        throw MathRuntimeException.createArithmeticException(LocalizedFormats.ARRAY_SUMS_TO_ZERO);
    }
    for (int i = 0; i < len; i++) {
        if (Double.isNaN(values[i])) {
            out[i] = Double.NaN;
        } else {
            out[i] = values[i] * normalizedSum / sum;
        }
    }
    return out;
}
 
Example #29
Source File: MultiStartUnivariateRealOptimizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public UnivariateRealPointValuePair optimize(final FUNC f,
                                             final GoalType goal,
                                             final double min, final double max)
    throws FunctionEvaluationException {

    optima = new UnivariateRealPointValuePair[starts];
    totalEvaluations = 0;

    // Multi-start loop.
    for (int i = 0; i < starts; ++i) {
        try {
            final double bound1 = (i == 0) ? min : min + generator.nextDouble() * (max - min);
            final double bound2 = (i == 0) ? max : min + generator.nextDouble() * (max - min);
            optima[i] = optimizer.optimize(f, goal,
                                           FastMath.min(bound1, bound2),
                                           FastMath.max(bound1, bound2));
        } catch (FunctionEvaluationException fee) {
            optima[i] = null;
        } catch (ConvergenceException ce) {
            optima[i] = null;
        }

        final int usedEvaluations = optimizer.getEvaluations();
        optimizer.setMaxEvaluations(optimizer.getMaxEvaluations() - usedEvaluations);
        totalEvaluations += usedEvaluations;
    }

    sortPairs(goal);

    if (optima[0] == null) {
        throw new ConvergenceException(LocalizedFormats.NO_CONVERGENCE_WITH_ANY_START_POINT,
                                       starts);
    }

    // Return the point with the best objective function value.
    return optima[0];
}
 
Example #30
Source File: ArrayRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a vector from part of a array.
 * @param d array of doubles.
 * @param pos position of first entry
 * @param size number of entries to copy
 */
public ArrayRealVector(double[] d, int pos, int size) {
    if (d.length < pos + size) {
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.POSITION_SIZE_MISMATCH_INPUT_ARRAY, pos, size, d.length);
    }
    data = new double[size];
    System.arraycopy(d, pos, data, 0, size);
}