org.apache.commons.math.MathRuntimeException Java Examples

The following examples show how to use org.apache.commons.math.MathRuntimeException. 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: Array2DRowRealMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public double[] operate(final double[] v)
    throws IllegalArgumentException {
    final int nRows = this.getRowDimension();
    final int nCols = this.getColumnDimension();
    if (v.length != nCols) {
        throw MathRuntimeException.createIllegalArgumentException(
              VECTOR_LENGTHS_MISMATCH, v.length, nCols);
    }
    final double[] out = new double[nRows];
    for (int row = 0; row < nRows; row++) {
        final double[] dataRow = data[row];
        double sum = 0;
        for (int i = 0; i < nCols; i++) {
            sum += dataRow[i] * v[i];
        }
        out[row] = sum;
    }
    return out;
}
 
Example #2
Source File: Cardumen_0053_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise a long 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 long pow(final long k, long e)
    throws IllegalArgumentException {

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

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

    return result;

}
 
Example #3
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the imaginary part of the k<sup>th</sup> n<sup>th</sup> root of unity
 * @param k index of the n<sup>th</sup> root of unity
 * @return imaginary part of the k<sup>th</sup> n<sup>th</sup> root of unity
 * @throws IllegalStateException if no roots of unity have been computed yet
 * @throws IllegalArgumentException if k is out of range
 */
public synchronized double getOmegaImaginary(int k)
  throws IllegalStateException, IllegalArgumentException {

  if (omegaCount == 0) {
      throw MathRuntimeException.createIllegalStateException(
              MISSING_ROOTS_OF_UNITY_MESSAGE);
  }
  if ((k < 0) || (k >= omegaCount)) {
    throw MathRuntimeException.createIllegalArgumentException(
            OUT_OF_RANGE_ROOT_INDEX_MESSAGE, k, 0, omegaCount - 1);
  }

  return isForward ? omegaImaginaryForward[k] : omegaImaginaryInverse[k];

}
 
Example #4
Source File: RandomDataImpl.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Uses a 2-cycle permutation shuffle to generate a random permutation.
 * <strong>Algorithm Description</strong>: Uses a 2-cycle permutation
 * shuffle to generate a random permutation of <code>c.size()</code> and
 * then returns the elements whose indexes correspond to the elements of the
 * generated permutation. This technique is described, and proven to
 * generate random samples, <a
 * href="http://www.maths.abdn.ac.uk/~igc/tch/mx4002/notes/node83.html">
 * here</a>
 * 
 * @param c
 *            Collection to sample from.
 * @param k
 *            sample size.
 * @return the random sample.
 */
public Object[] nextSample(Collection<?> c, int k) {
    int len = c.size();
    if (k > len) {
        throw MathRuntimeException.createIllegalArgumentException(
              "sample size ({0}) exceeds collection size ({1})");
    }
    if (k <= 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "sample size must be positive ({0})", k);
    }

    Object[] objects = c.toArray();
    int[] index = nextPermutation(len, k);
    Object[] result = new Object[k];
    for (int i = 0; i < k; i++) {
        result[i] = objects[index[i]];
    }
    return result;
}
 
Example #5
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(
              "must have n >= 0 for n!, got n = {0}",
              n);
    }
    if (n < 21) {
        return Math.log(factorial(n));
    }
    double logSum = 0;
    for (int i = 2; i <= n; i++) {
        logSum += Math.log(i);
    }
    return logSum;
}
 
Example #6
Source File: Cardumen_0053_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 #7
Source File: RealMatrixImpl.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public double[] preMultiply(final double[] v)
    throws IllegalArgumentException {

    final int nRows = getRowDimension();
    final int nCols = getColumnDimension();
    if (v.length != nRows) {
        throw MathRuntimeException.createIllegalArgumentException(
                "vector length mismatch: got {0} but expected {1}",
                v.length, nRows);
    }

    final double[] out = new double[nCols];
    for (int col = 0; col < nCols; ++col) {
        double sum = 0;
        for (int i = 0; i < nRows; ++i) {
            sum += data[i][col] * v[i];
        }
        out[col] = sum;
    }

    return out;

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

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

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

    return result;

}
 
Example #9
Source File: EmpiricalDistributionImpl.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a random value from this distribution.
 *
 * @return the random value.
 * @throws IllegalStateException if the distribution has not been loaded
 */
public double getNextValue() throws IllegalStateException {

    if (!loaded) {
        throw MathRuntimeException.createIllegalStateException("distribution not loaded");
    }

    // Start with a uniformly distributed random number in (0,1)
    double x = Math.random();

    // Use this to select the bin and generate a Gaussian within the bin
    for (int i = 0; i < binCount; i++) {
       if (x <= upperBounds[i]) {
           SummaryStatistics stats = binStats.get(i);
           if (stats.getN() > 0) {
               if (stats.getStandardDeviation() > 0) {  // more than one obs
                    return randomData.nextGaussian
                        (stats.getMean(),stats.getStandardDeviation());
               } else {
                   return stats.getMean(); // only one obs in bin
               }
           }
       }
    }
    throw new MathRuntimeException("no bin selected");
}
 
Example #10
Source File: Vector3D.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Compute the angular separation between two vectors.
 * <p>This method computes the angular separation between two
 * vectors using the dot product for well separated vectors and the
 * cross product for almost aligned vectors. This allows to have a
 * good accuracy in all cases, even for vectors very close to each
 * other.</p>
 * @param v1 first vector
 * @param v2 second vector
 * @return angular separation between v1 and v2
 * @exception ArithmeticException if either vector has a null norm
 */
public static double angle(Vector3D v1, Vector3D v2) {

  double normProduct = v1.getNorm() * v2.getNorm();
  if (normProduct == 0) {
    throw MathRuntimeException.createArithmeticException("zero norm");
  }

  double dot = dotProduct(v1, v2);
  double threshold = normProduct * 0.9999;
  if ((dot < -threshold) || (dot > threshold)) {
    // the vectors are almost aligned, compute using the sine
    Vector3D v3 = crossProduct(v1, v2);
    if (dot >= 0) {
      return Math.asin(v3.getNorm() / normProduct);
    }
    return Math.PI - Math.asin(v3.getNorm() / normProduct);
  }

  // the vectors are sufficiently separated to use the cosine
  return Math.acos(dot / normProduct);

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

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

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

    return result;

}
 
Example #12
Source File: FractionFormat.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats an object and appends the result to a StringBuffer. <code>obj</code> must be either a
 * {@link Fraction} object or a {@link Number} object.  Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws IllegalArgumentException is <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(final Object obj,
                           final StringBuffer toAppendTo, final FieldPosition pos) {
    StringBuffer ret = null;

    if (obj instanceof Fraction) {
        ret = format((Fraction) obj, toAppendTo, pos);
    } else if (obj instanceof Number) {
        try {
            ret = format(new Fraction(((Number) obj).doubleValue()),
                         toAppendTo, pos);
        } catch (ConvergenceException ex) {
            throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.CANNOT_CONVERT_OBJECT_TO_FRACTION,
                ex.getLocalizedMessage());
        }
    } else {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.CANNOT_FORMAT_OBJECT_TO_FRACTION);
    }

    return ret;
}
 
Example #13
Source File: AbstractRealMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public RealVector operate(final RealVector v)
    throws IllegalArgumentException {
    try {
        return new ArrayRealVector(operate(((ArrayRealVector) v).getDataRef()), false);
    } catch (ClassCastException cce) {
        final int nRows = getRowDimension();
        final int nCols = getColumnDimension();
        if (v.getDimension() != nCols) {
            throw MathRuntimeException.createIllegalArgumentException(
                    LocalizedFormats.VECTOR_LENGTH_MISMATCH,
                    v.getDimension(), nCols);
        }

        final double[] out = new double[nRows];
        for (int row = 0; row < nRows; ++row) {
            double sum = 0;
            for (int i = 0; i < nCols; ++i) {
                sum += getEntry(row, i) * v.getEntry(i);
            }
            out[row] = sum;
        }

        return new ArrayRealVector(out, false);
    }
}
 
Example #14
Source File: MathUtils.java    From astor with GNU General Public License v2.0 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(
            "cannot raise an integral value to a negative power ({0}^{1})",
            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 #15
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a matrix element.
 * @param vector indices of the element
 * @return matrix element
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex get(int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                DIMENSION_MISMATCH_MESSAGE, vector.length, dimensionSize.length);
    }

    Object lastDimension = multiDimensionalComplexArray;

    for (int i = 0; i < dimensionSize.length; i++) {
        lastDimension = ((Object[]) lastDimension)[vector[i]];
    }
    return (Complex) lastDimension;
}
 
Example #16
Source File: UnivariateRealIntegratorImpl.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Access the last computed integral.
 * 
 * @return the last computed integral
 * @throws IllegalStateException if no integral has been computed
 */
public double getResult() throws IllegalStateException {
    if (resultComputed) {
        return result;
    } else {
        throw MathRuntimeException.createIllegalStateException("no result available");
    }
}
 
Example #17
Source File: PolynomialFunctionNewtonForm.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that the input arrays are valid.
 * <p>
 * The centers must be distinct for interpolation purposes, but not
 * for general use. Thus it is not verified here.</p>
 *
 * @param a the coefficients in Newton form formula
 * @param c the centers
 * @throws IllegalArgumentException if not valid
 * @see org.apache.commons.math.analysis.interpolation.DividedDifferenceInterpolator#computeDividedDifference(double[],
 * double[])
 */
protected static void verifyInputArray(double a[], double c[]) throws
    IllegalArgumentException {

    if (a.length < 1 || c.length < 1) {
        throw MathRuntimeException.createIllegalArgumentException(
              "empty polynomials coefficients array");
    }
    if (a.length != c.length + 1) {
        throw MathRuntimeException.createIllegalArgumentException(
              "array sizes should have difference 1 ({0} != {1} + 1)",
              a.length, c.length);
    }
}
 
Example #18
Source File: Complex.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Computes the n-th roots of this complex number.
 * </p>
 * <p>The nth roots are defined by the formula: <pre>
 * <code> z<sub>k</sub> = abs<sup> 1/n</sup> (cos(phi + 2&pi;k/n) + i (sin(phi + 2&pi;k/n))</code></pre>
 * for <i><code>k=0, 1, ..., n-1</code></i>, where <code>abs</code> and <code>phi</code> are
 * respectively the {@link #abs() modulus} and {@link #getArgument() argument} of this complex number.
 * </p>
 * <p>If one or both parts of this complex number is NaN, a list with just one element,
 *  {@link #NaN} is returned.</p>
 * <p>if neither part is NaN, but at least one part is infinite, the result is a one-element
 * list containing {@link #INF}.</p>
 *
 * @param n degree of root
 * @return List<Complex> all nth roots of this complex number
 * @throws IllegalArgumentException if parameter n is less than or equal to 0
 * @since 2.0
 */
public List<Complex> nthRoot(int n) throws IllegalArgumentException {

    if (n <= 0) {
        throw MathRuntimeException.createIllegalArgumentException(
                "cannot compute nth root for null or negative n: {0}",
                n);
    }

    List<Complex> result = new ArrayList<Complex>();

    if (isNaN()) {
        result.add(Complex.NaN);
        return result;
    }

    if (isInfinite()) {
        result.add(Complex.INF);
        return result;
    }

    // nth root of abs -- faster / more accurate to use a solver here?
    final double nthRootOfAbs = Math.pow(abs(), 1.0 / n);

    // Compute nth roots of complex number with k = 0, 1, ... n-1
    final double nthPhi = getArgument()/n;
    final double slice = 2 * Math.PI / n;
    double innerPart = nthPhi;
    for (int k = 0; k < n ; k++) {
        // inner part
        final double realPart      = nthRootOfAbs *  Math.cos(innerPart);
        final double imaginaryPart = nthRootOfAbs *  Math.sin(innerPart);
        result.add(createComplex(realPart, imaginaryPart));
        innerPart += slice;
    }

    return result;
}
 
Example #19
Source File: AbstractMultipleLinearRegression.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 *             matrix are not compatible for the regression
 */
protected void validateCovarianceData(double[][] x, double[][] covariance) {
    if (x.length != covariance.length) {
        throw MathRuntimeException.createIllegalArgumentException(
             "dimension mismatch {0} != {1}", x.length, covariance.length);
    }
    if (covariance.length > 0 && covariance.length != covariance[0].length) {
        throw MathRuntimeException.createIllegalArgumentException(
              "a {0}x{1} matrix was provided instead of a square matrix",
              covariance.length, covariance[0].length);
    }
}
 
Example #20
Source File: AbstractFormat.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Modify the numerator format.
 * @param format the new numerator format value.
 * @throws IllegalArgumentException if <code>format</code> is
 *         <code>null</code>.
 */
public void setNumeratorFormat(final NumberFormat format) {
    if (format == null) {
        throw MathRuntimeException.createIllegalArgumentException(
            "numerator format can not be null");
    }
    this.numeratorFormat = format;
}
 
Example #21
Source File: JGenProg2017_00119_s.java    From coming with MIT License 5 votes vote down vote up
/** Solve the linear equation A &times; X = B for symmetric matrices A.
 * <p>This method only find exact linear solutions, i.e. solutions for
 * which ||A &times; X - B|| is exactly 0.</p>
 * @param b right-hand side of the equation A &times; X = B
 * @return a vector X that minimizes the two norm of A &times; X - B
 * @exception IllegalArgumentException if matrices dimensions don't match
 * @exception InvalidMatrixException if decomposed matrix is singular
 */
public RealVector solve(final RealVector b)
    throws IllegalArgumentException, InvalidMatrixException {

    if (!isNonSingular()) {
        throw new SingularMatrixException();
    }

    final int m = realEigenvalues.length;
    if (b.getDimension() != m) {
        throw MathRuntimeException.createIllegalArgumentException(
                "vector length mismatch: got {0} but expected {1}",
                b.getDimension(), m);
    }

    final double[] bp = new double[m];
    for (int i = 0; i < m; ++i) {
        final ArrayRealVector v = eigenvectors[i];
        final double[] vData = v.getDataRef();
        final double s = v.dotProduct(b) / realEigenvalues[i];
        for (int j = 0; j < m; ++j) {
            bp[j] += s * vData[j];
        }
    }

    return new ArrayRealVector(bp, false);

}
 
Example #22
Source File: MathUtils.java    From astor with GNU General Public License v2.0 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(
            "must have n >= k for binomial coefficient (n,k), got n = {0}, k = {1}",
            n, k);
    }
    if (n < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "must have n >= 0 for binomial coefficient (n,k), got n = {0}",
              n);
    }
}
 
Example #23
Source File: ChiSquareTestImpl.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check all entries of the input array are >= 0.
 * 
 * @param in array to be tested
 * @exception IllegalArgumentException if one entry is negative
 */
private void checkNonNegative(long[][] in) throws IllegalArgumentException {
    for (int i = 0; i < in.length; i ++) {
        for (int j = 0; j < in[i].length; j++) {
            if (in[i][j] < 0) {
                throw MathRuntimeException.createIllegalArgumentException(
                      "element ({0}, {1}) is negative: {2}",
                      i, j, in[i][j]);
            }
        }
    }
}
 
Example #24
Source File: WeibullDistributionImpl.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Modify the shape parameter.
 * @param alpha the new shape parameter value.
 */
public void setShape(double alpha) {
    if (alpha <= 0.0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "shape must be positive ({0})",
              alpha);
    }
    this.shape = alpha;
}
 
Example #25
Source File: LaguerreSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find a real root in the given interval.
 * <p>
 * Despite the bracketing condition, the root returned by solve(Complex[],
 * Complex) may not be a real zero inside [min, max]. For example,
 * p(x) = x^3 + 1, min = -2, max = 2, initial = 0. We can either try
 * another initial value, or, as we did here, call solveAll() to obtain
 * all roots and pick up the one that we're looking for.</p>
 *
 * @param f the function to solve
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @return the point at which the function value is zero
 * @throws ConvergenceException if the maximum iteration count is exceeded
 * or the solver detects convergence problems otherwise
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 * @throws IllegalArgumentException if any parameters are invalid
 */
public double solve(final UnivariateRealFunction f,
                    final double min, final double max)
    throws ConvergenceException, FunctionEvaluationException {

    // check function type
    if (!(f instanceof PolynomialFunction)) {
        throw MathRuntimeException.createIllegalArgumentException(NON_POLYNOMIAL_FUNCTION_MESSAGE);
    }

    // check for zeros before verifying bracketing
    if (f.value(min) == 0.0) { return min; }
    if (f.value(max) == 0.0) { return max; }
    verifyBracketing(min, max, f);

    double coefficients[] = ((PolynomialFunction) f).getCoefficients();
    Complex c[] = new Complex[coefficients.length];
    for (int i = 0; i < coefficients.length; i++) {
        c[i] = new Complex(coefficients[i], 0.0);
    }
    Complex initial = new Complex(0.5 * (min + max), 0.0);
    Complex z = solve(c, initial);
    if (isRootOK(min, max, z)) {
        setResult(z.getReal(), iterationCount);
        return result;
    }

    // solve all roots and select the one we're seeking
    Complex[] root = solveAll(c, initial);
    for (int i = 0; i < root.length; i++) {
        if (isRootOK(min, max, root[i])) {
            setResult(root[i].getReal(), iterationCount);
            return result;
        }
    }

    // should never happen
    throw new ConvergenceException();
}
 
Example #26
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set a matrix element.
 * @param magnitude magnitude of the element
 * @param vector indices of the element
 * @return the previous value
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex set(Complex magnitude, int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    "some dimensions don't match: {0} != {1}",
                    0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                "some dimensions don't match: {0} != {1}",
                vector.length,dimensionSize.length);
    }

    Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
    for (int i = 0; i < dimensionSize.length - 1; i++) {
        lastDimension = (Object[]) lastDimension[vector[i]];
    }

    Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
    lastDimension[vector[dimensionSize.length - 1]] = magnitude;

    return lastValue;
}
 
Example #27
Source File: MatrixUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #28
Source File: LegendreGaussIntegrator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Build a Legendre-Gauss integrator.
 * @param n number of points desired (must be between 2 and 5 inclusive)
 * @param defaultMaximalIterationCount maximum number of iterations
 * @exception IllegalArgumentException if the number of points is not
 * in the supported range
 */
public LegendreGaussIntegrator(final int n, final int defaultMaximalIterationCount)
    throws IllegalArgumentException {
    super(defaultMaximalIterationCount);
    switch(n) {
    case 2 :
        abscissas = ABSCISSAS_2;
        weights   = WEIGHTS_2;
        break;
    case 3 :
        abscissas = ABSCISSAS_3;
        weights   = WEIGHTS_3;
        break;
    case 4 :
        abscissas = ABSCISSAS_4;
        weights   = WEIGHTS_4;
        break;
    case 5 :
        abscissas = ABSCISSAS_5;
        weights   = WEIGHTS_5;
        break;
    default :
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.N_POINTS_GAUSS_LEGENDRE_INTEGRATOR_NOT_SUPPORTED,
                n, 2, 5);
    }

}
 
Example #29
Source File: ProperFractionFormat.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Modify the whole format.
 * @param format The new whole format value.
 * @throws IllegalArgumentException if <code>format</code> is
 *         <code>null</code>.
 */
public void setWholeFormat(NumberFormat format) {
    if (format == null) {
        throw MathRuntimeException.createIllegalArgumentException(
            "whole format can not be null");
    }
    this.wholeFormat = format;
}
 
Example #30
Source File: Arja_00183_s.java    From coming with MIT License 5 votes vote down vote up
/** Solve the linear equation A &times; X = B for symmetric matrices A.
 * <p>This method only find exact linear solutions, i.e. solutions for
 * which ||A &times; X - B|| is exactly 0.</p>
 * @param b right-hand side of the equation A &times; X = B
 * @return a matrix X that minimizes the two norm of A &times; X - B
 * @exception IllegalArgumentException if matrices dimensions don't match
 * @exception InvalidMatrixException if decomposed matrix is singular
 */
public RealMatrix solve(final RealMatrix b)
    throws IllegalArgumentException, InvalidMatrixException {

    if (!isNonSingular()) {
        throw new SingularMatrixException();
    }

    final int m = realEigenvalues.length;
    if (b.getRowDimension() != m) {
        throw MathRuntimeException.createIllegalArgumentException(
                "dimensions mismatch: got {0}x{1} but expected {2}x{3}",
                b.getRowDimension(), b.getColumnDimension(), m, "n");
    }

    final int nColB = b.getColumnDimension();
    final double[][] bp = new double[m][nColB];
    for (int k = 0; k < nColB; ++k) {
        for (int i = 0; i < m; ++i) {
            final ArrayRealVector v = eigenvectors[i];
            final double[] vData = v.getDataRef();
            double s = 0;
            for (int j = 0; j < m; ++j) {
                s += v.getEntry(j) * b.getEntry(j, k);
            }
            s /= realEigenvalues[i];
            for (int j = 0; j < m; ++j) {
                bp[j][k] += s * vData[j];
            }
        }
    }

    return MatrixUtils.createRealMatrix(bp);

}