Java Code Examples for org.apache.commons.math.util.MathUtils

The following examples show how to use org.apache.commons.math.util.MathUtils. These examples are extracted from open source projects. 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 Project: coming   Source File: jMutRepair_0015_s.java    License: MIT License 6 votes vote down vote up
/**
 * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
 * @param tableau simple tableau for the problem
 * @param col the column to test the ratio of.  See {@link #getPivotColumn(SimplexTableau)}
 * @return row with the minimum ratio
 */
private Integer getPivotRow(final int col, final SimplexTableau tableau) {
    double minRatio = Double.MAX_VALUE;
    Integer minRatioPos = null;
    for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
        final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
        final double entry = tableau.getEntry(i, col);
        if (MathUtils.compareTo(entry, 0, epsilon) >= 0) {
            final double ratio = rhs / entry;
            if (ratio < minRatio) {
                minRatio = ratio;
                minRatioPos = i; 
            }
        }
    }
    return minRatioPos;
}
 
Example 2
Source Project: coming   Source File: Cardumen_00275_s.java    License: MIT License 6 votes vote down vote up
/**
 * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
 * @param tableau simple tableau for the problem
 * @param col the column to test the ratio of.  See {@link #getPivotColumn(SimplexTableau)}
 * @return row with the minimum ratio
 */
private Integer getPivotRow(final int col, final SimplexTableau tableau) {
    double minRatio = Double.MAX_VALUE;
    Integer minRatioPos = null;
    for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
        final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
        final double entry = tableau.getEntry(i, col);
        if (MathUtils.compareTo(entry, 0, epsilon) >= 0) {
            final double ratio = rhs / entry;
            if (ratio < minRatio) {
                minRatio = ratio;
                minRatioPos = i; 
            }
        }
    }
    return minRatioPos;
}
 
Example 3
Source Project: astor   Source File: HarmonicFitterTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testNoError() throws OptimizationException {
    HarmonicFunction f = new HarmonicFunction(0.2, 3.4, 4.1);

    HarmonicFitter fitter =
        new HarmonicFitter(new LevenbergMarquardtOptimizer());
    for (double x = 0.0; x < 1.3; x += 0.01) {
        fitter.addObservedPoint(1.0, x, f.value(x));
    }

    HarmonicFunction fitted = fitter.fit();
    assertEquals(f.getAmplitude(), fitted.getAmplitude(), 1.0e-13);
    assertEquals(f.getPulsation(), fitted.getPulsation(), 1.0e-13);
    assertEquals(f.getPhase(),     MathUtils.normalizeAngle(fitted.getPhase(), f.getPhase()), 1.0e-13);

    for (double x = -1.0; x < 1.0; x += 0.01) {
        assertTrue(Math.abs(f.value(x) - fitted.value(x)) < 1.0e-13);
    }

}
 
Example 4
Source Project: coming   Source File: JGenProg2017_0071_t.java    License: MIT License 6 votes vote down vote up
/**
 * Check if a matrix is symmetric.
 * @param matrix matrix to check
 * @return true if matrix is symmetric
 */
private boolean isSymmetric(final RealMatrix matrix) {
    final int rows    = matrix.getRowDimension();
    final int columns = matrix.getColumnDimension();
    final double eps  = 10 * rows * columns * MathUtils.EPSILON;
    for (int i = 0; i < rows; ++i) {
        for (int j = i + 1; j < columns; ++j) {
            final double mij = matrix.getEntry(i, j);
            final double mji = matrix.getEntry(j, i);
            if (Math.abs(mij - mji) > (Math.max(Math.abs(mij), Math.abs(mji)) * eps)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 5
Source Project: coming   Source File: Cardumen_00182_t.java    License: MIT License 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @exception OptimizationException if the maximal number of iterations is
 * exceeded, or if the problem is found not to have a bounded solution, or
 * if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws OptimizationException {
    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!isPhase1Solved(tableau)) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!MathUtils.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 6
Source Project: astor   Source File: VarianceTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testWeightedVariance() {
    Variance variance = new Variance();
    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());

}
 
Example 7
Source Project: coming   Source File: Arja_0036_s.java    License: MIT License 6 votes vote down vote up
/**
 * Create a counter.
 *
 * @param size Counter sizes (number of slots in each dimension).
 * @throws NotStrictlyPositiveException if one of the sizes is
 * negative or zero.
 */
public MultidimensionalCounter(int ... size) {
    dimension = size.length;
    this.size = MathUtils.copyOf(size);

    uniCounterOffset = new int[dimension];

    last = dimension - 1;
    int tS = size[last];
    for (int i = 0; i < last; i++) {
        int count = 1;
        for (int j = i + 1; j < dimension; j++) {
            count *= size[j];
        }
        uniCounterOffset[i] = count;
        tS *= size[i];
    }
    uniCounterOffset[last] = 0;

    if (tS <= 0) {
        throw new NotStrictlyPositiveException(tS);
    }

    totalSize = tS;
}
 
Example 8
Source Project: coming   Source File: Cardumen_00185_s.java    License: MIT License 6 votes vote down vote up
/**
 * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
 * @param tableau simple tableau for the problem
 * @param col the column to test the ratio of.  See {@link #getPivotColumn()}
 * @return row with the minimum ratio
 */
private Integer getPivotRow(final int col, final SimplexTableau tableau) {
    double minRatio = Double.MAX_VALUE;
    Integer minRatioPos = null;
    for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
        double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
        if (MathUtils.compareTo(tableau.getEntry(i, col), 0, epsilon) >= 0) {
            double ratio = rhs / tableau.getEntry(i, col);
            if (ratio < minRatio) {
                minRatio = ratio;
                minRatioPos = i; 
            }
        }
    }
    return minRatioPos;
}
 
Example 9
Source Project: astor   Source File: SaddlePointExpansion.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compute the PMF for a binomial distribution using the saddle point
 * expansion.
 *
 * @param x the value at which the probability is evaluated.
 * @param n the number of trials.
 * @param p the probability of success.
 * @param q the probability of failure (1 - p).
 * @return log(p(x)).
 */
static double logBinomialProbability(int x, int n, double p, double q) {
    double ret;
    if (x == 0) {
        if (p < 0.1) {
            ret = -getDeviancePart(n, n * q) - n * p;
        } else {
            ret = n * FastMath.log(q);
        }
    } else if (x == n) {
        if (q < 0.1) {
            ret = -getDeviancePart(n, n * p) - n * q;
        } else {
            ret = n * FastMath.log(p);
        }
    } else {
        ret = getStirlingError(n) - getStirlingError(x) -
              getStirlingError(n - x) - getDeviancePart(x, n * p) -
              getDeviancePart(n - x, n * q);
        double f = (MathUtils.TWO_PI * x * (n - x)) / n;
        ret = -0.5 * FastMath.log(f) + ret;
    }
    return ret;
}
 
Example 10
Source Project: astor   Source File: SummaryStatistics.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns true iff <code>object</code> is a
 * <code>SummaryStatistics</code> instance and all statistics have the
 * same values as this.
 * @param object the object to test equality against.
 * @return true if object equals this
 */
@Override
public boolean equals(Object object) {
    if (object == this) {
        return true;
    }
    if (object instanceof SummaryStatistics == false) {
        return false;
    }
    SummaryStatistics stat = (SummaryStatistics)object;
    return MathUtils.equals(stat.getGeometricMean(), getGeometricMean()) &&
           MathUtils.equals(stat.getMax(),           getMax())           &&
           MathUtils.equals(stat.getMean(),          getMean())          &&
           MathUtils.equals(stat.getMin(),           getMin())           &&
           MathUtils.equals(stat.getN(),             getN())             &&
           MathUtils.equals(stat.getSum(),           getSum())           &&
           MathUtils.equals(stat.getSumsq(),         getSumsq())         &&
           MathUtils.equals(stat.getVariance(),      getVariance());
}
 
Example 11
Source Project: astor   Source File: VarianceTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testWeightedVariance() {
    Variance variance = new Variance();
    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());

}
 
Example 12
public void checkremoval(DescriptiveStatistics dstat, int wsize,
                         double mean1, double mean2, double mean3) {

    dstat.setWindowSize(wsize);
    dstat.clear();

    for (int i = 1 ; i <= 6 ; ++i) {
        dstat.addValue(i);
    }

    assertTrue(MathUtils.equals(mean1, dstat.getMean()));
    dstat.replaceMostRecentValue(0);
    assertTrue(MathUtils.equals(mean2, dstat.getMean()));
    dstat.removeMostRecentValue();
    assertTrue(MathUtils.equals(mean3, dstat.getMean()));

}
 
Example 13
/**
 * Construct the exception.
 *
 * @param wrong Value that did not match the requirements.
 * @param previous Previous value in the sequence.
 * @param index Index of the value that did not match the requirements.
 * @param direction Strictly positive for a sequence required to be
 * increasing, negative (or zero) for a decreasing sequence.
 * @param strict Whether the sequence must be strictly increasing or
 * decreasing.
 */
public NonMonotonousSequenceException(Number wrong,
                                      Number previous,
                                      int index,
                                      MathUtils.OrderDirection direction,
                                      boolean strict) {
    super(direction == MathUtils.OrderDirection.INCREASING ?
          (strict ?
           LocalizedFormats.NOT_STRICTLY_INCREASING_SEQUENCE :
           LocalizedFormats.NOT_INCREASING_SEQUENCE) :
          (strict ?
           LocalizedFormats.NOT_STRICTLY_DECREASING_SEQUENCE :
           LocalizedFormats.NOT_DECREASING_SEQUENCE),
          wrong, previous, index, index - 1);

    this.direction = direction;
    this.strict = strict;
    this.index = index;
    this.previous = previous;
}
 
Example 14
Source Project: astor   Source File: EigenDecompositionImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if a matrix is symmetric.
 * @param matrix
 *            matrix to check
 * @return true if matrix is symmetric
 */
private boolean isSymmetric(final RealMatrix matrix) {
    final int rows = matrix.getRowDimension();
    final int columns = matrix.getColumnDimension();
    final double eps = 10 * rows * columns * MathUtils.EPSILON;
    for (int i = 0; i < rows; ++i) {
        for (int j = i + 1; j < columns; ++j) {
            final double mij = matrix.getEntry(i, j);
            final double mji = matrix.getEntry(j, i);
            if (Math.abs(mij - mji) > (Math.max(Math.abs(mij), Math
                    .abs(mji)) * eps)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 15
/**
 * Verifies operation on indefinite matrix
 */
public void testZeroDivide() {
    RealMatrix indefinite = MatrixUtils.createRealMatrix(new double [][] {
            { 0.0, 1.0, -1.0 },
            { 1.0, 1.0, 0.0 },
            { -1.0,0.0, 1.0 }
    });
    EigenDecomposition ed = new EigenDecompositionImpl(indefinite, MathUtils.SAFE_MIN);
    checkEigenValues((new double[] {2, 1, -1}), ed, 1E-12);
    double isqrt3 = 1/Math.sqrt(3.0);
    checkEigenVector((new double[] {isqrt3,isqrt3,-isqrt3}), ed, 1E-12);
    double isqrt2 = 1/Math.sqrt(2.0);
    checkEigenVector((new double[] {0.0,-isqrt2,-isqrt2}), ed, 1E-12);
    double isqrt6 = 1/Math.sqrt(6.0);
    checkEigenVector((new double[] {2*isqrt6,-isqrt6,isqrt6}), ed, 1E-12);
}
 
Example 16
Source Project: astor   Source File: AbstractRealMatrix.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Computes a hashcode for the matrix.
 *
 * @return hashcode for matrix
 */
@Override
public int hashCode() {
    int ret = 7;
    final int nRows = getRowDimension();
    final int nCols = getColumnDimension();
    ret = ret * 31 + nRows;
    ret = ret * 31 + nCols;
    for (int row = 0; row < nRows; ++row) {
        for (int col = 0; col < nCols; ++col) {
           ret = ret * 31 + (11 * (row+1) + 17 * (col+1)) *
               MathUtils.hash(getEntry(row, col));
       }
    }
    return ret;
}
 
Example 17
Source Project: coming   Source File: Arja_00171_t.java    License: MIT License 6 votes vote down vote up
/**
 * Check if a matrix is symmetric.
 * @param matrix matrix to check
 * @return true if matrix is symmetric
 */
private boolean isSymmetric(final RealMatrix matrix) {
    final int rows    = matrix.getRowDimension();
    final int columns = matrix.getColumnDimension();
    final double eps  = 10 * rows * columns * MathUtils.EPSILON;
    for (int i = 0; i < rows; ++i) {
        for (int j = i + 1; j < columns; ++j) {
            final double mij = matrix.getEntry(i, j);
            final double mji = matrix.getEntry(j, i);
            if (Math.abs(mij - mji) > (Math.max(Math.abs(mij), Math.abs(mji)) * eps)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 18
Source Project: astor   Source File: Line.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Reset the instance as if built from a line and an angle.
 * @param p point belonging to the line
 * @param alpha angle of the line with respect to abscissa axis
 */
public void reset(final Vector2D p, final double alpha) {
    this.angle   = MathUtils.normalizeAngle(alpha, FastMath.PI);
    cos          = FastMath.cos(this.angle);
    sin          = FastMath.sin(this.angle);
    originOffset = cos * p.getY() - sin * p.getX();
}
 
Example 19
/**
 * Create a fraction given the numerator and denominator.  The fraction is
 * reduced to lowest terms.
 * @param num the numerator.
 * @param den the denominator.
 * @throws ArithmeticException if the denomiator is <code>zero</code>
 */
public Fraction(int num, int den) {
    super();
    if (den == 0) {
        throw new ArithmeticException("The denominator must not be zero");
    }
    if (den < 0) {
        if (num == Integer.MIN_VALUE ||
                den == Integer.MIN_VALUE) {
            throw new ArithmeticException("overflow: can't negate");
        }
        num = -num;
        den = -den;
    }
    // reduce numerator and denominator by greatest common denominator.
    int d = MathUtils.gcd(num, den);
    if (d > 1) {
        num /= d;
        den /= d;
    }
    
    // move sign to numerator.
    if (den < 0) {
        num *= -1;
        den *= -1;
    }
    this.numerator = num;
    this.denominator = den;
}
 
Example 20
Source Project: astor   Source File: SimplexSolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the problem is at an optimal state.
 * @param tableau simple tableau for the problem
 * @return whether the model has been solved
 */
public boolean isOptimal(final SimplexTableau tableau) {
    if (tableau.getNumArtificialVariables() > 0) {
        return false;
    }
    for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
        if (MathUtils.compareTo(tableau.getEntry(0, i), 0, epsilon) < 0) {
            return false;
        }
    }
    return true;
}
 
Example 21
/**
 * Matrix with eigenvalues {8, -1, -1}
 */
public void testRepeatedEigenvalue() {
    RealMatrix repeated = MatrixUtils.createRealMatrix(new double[][] {
            {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);
}
 
Example 22
Source Project: coming   Source File: Cardumen_0066_s.java    License: MIT License 5 votes vote down vote up
/**
 * Returns whether the problem is at an optimal state.
 * @param tableau simple tableau for the problem
 * @return whether the model has been solved
 */
public boolean isOptimal(final SimplexTableau tableau) {
    if (tableau.getNumArtificialVariables() > 0) {
        return false;
    }
    for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
        if (MathUtils.compareTo(tableau.getEntry(0, i), 0, epsilon) < 0) {
            return false;
        }
    }
    return true;
}
 
Example 23
Source Project: astor   Source File: SimplexSolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
 * @param tableau simple tableau for the problem
 * @param col the column to test the ratio of.  See {@link #getPivotColumn(SimplexTableau)}
 * @return row with the minimum ratio
 */
private Integer getPivotRow(SimplexTableau tableau, final int col) {
    // create a list of all the rows that tie for the lowest score in the minimum ratio test
    List<Integer> minRatioPositions = new ArrayList<Integer>();
    double minRatio = Double.MAX_VALUE;
    for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
        final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
        final double entry = tableau.getEntry(i, col);
        if (MathUtils.compareTo(entry, 0, epsilon) > 0) {
            final double ratio = rhs / entry;
            if (MathUtils.equals(ratio, minRatio, epsilon)) {
                minRatioPositions.add(i);
            } else if (ratio < minRatio) {
                minRatio = ratio;
                minRatioPositions = new ArrayList<Integer>();
                minRatioPositions.add(i);
            }
        }
    }

    if (minRatioPositions.size() == 0) {
      return null;
    } else if (minRatioPositions.size() > 1) {
      // there's a degeneracy as indicated by a tie in the minimum ratio test
      // check if there's an artificial variable that can be forced out of the basis
      for (Integer row : minRatioPositions) {
        for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
          int column = i + tableau.getArtificialVariableOffset();
          if (MathUtils.equals(tableau.getEntry(row, column), 1, epsilon) &&
              row.equals(tableau.getBasicRow(column))) {
            return row;
          }
        }
      }
    }
    return minRatioPositions.get(0);
}
 
Example 24
public void testDimension2() {
    RealMatrix matrix =
        MatrixUtils.createRealMatrix(new double[][] {
                { 59.0, 12.0 },
                { 12.0, 66.0 }
        });
    EigenDecomposition ed = new EigenDecompositionImpl(matrix, MathUtils.SAFE_MIN);
    assertEquals(75.0, ed.getRealEigenvalue(0), 1.0e-15);
    assertEquals(50.0, ed.getRealEigenvalue(1), 1.0e-15);
}
 
Example 25
Source Project: astor   Source File: KalmanFilter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Correct the current state estimate with an actual measurement.
 *
 * @param z
 *            the measurement vector
 * @throws DimensionMismatchException
 *             if the dimension of the measurement vector does not fit
 * @throws org.apache.commons.math.linear.SingularMatrixException
 *             if the covariance matrix could not be inverted
 */
public void correct(final RealVector z) {
    // sanity checks
    MathUtils.checkNotNull(z);
    if (z.getDimension() != measurementMatrix.getRowDimension()) {
        throw new DimensionMismatchException(z.getDimension(),
                                             measurementMatrix.getRowDimension());
    }

    // S = H * P(k) - * H' + R
    RealMatrix s = measurementMatrix.multiply(errorCovariance)
        .multiply(measurementMatrixT)
        .add(measurementModel.getMeasurementNoise());

    // invert S
    // as the error covariance matrix is a symmetric positive
    // semi-definite matrix, we can use the cholesky decomposition
    DecompositionSolver solver = new CholeskyDecompositionImpl(s).getSolver();
    RealMatrix invertedS = solver.getInverse();

    // Inn = z(k) - H * xHat(k)-
    RealVector innovation = z.subtract(measurementMatrix.operate(stateEstimation));

    // calculate gain matrix
    // K(k) = P(k)- * H' * (H * P(k)- * H' + R)^-1
    // K(k) = P(k)- * H' * S^-1
    RealMatrix kalmanGain = errorCovariance.multiply(measurementMatrixT).multiply(invertedS);

    // update estimate with measurement z(k)
    // xHat(k) = xHat(k)- + K * Inn
    stateEstimation = stateEstimation.add(kalmanGain.operate(innovation));

    // update covariance of prediction error
    // P(k) = (I - K * H) * P(k)-
    RealMatrix identity = MatrixUtils.createRealIdentityMatrix(kalmanGain.getRowDimension());
    errorCovariance = identity.subtract(kalmanGain.multiply(measurementMatrix)).multiply(errorCovariance);
}
 
Example 26
Source Project: astor   Source File: EigenSolverTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** test non invertible matrix */
@Test
public void testNonInvertible() {
    Random r = new Random(9994100315209l);
    RealMatrix m =
        EigenDecompositionImplTest.createTestMatrix(r, new double[] { 1.0, 0.0, -1.0, -2.0, -3.0 });
    DecompositionSolver es = new EigenDecompositionImpl(m, MathUtils.SAFE_MIN).getSolver();
    Assert.assertFalse(es.isNonSingular());
    try {
        es.getInverse();
        Assert.fail("an exception should have been thrown");
    } catch (SingularMatrixException ime) {
        // expected behavior
    }
}
 
Example 27
Source Project: coming   Source File: Cardumen_0044_s.java    License: MIT License 5 votes vote down vote up
/**
 * Get a hashCode for the complex number.
 * Any {@code Double.NaN} value in real or imaginary part produces
 * the same hash code {@code 7}.
 *
 * @return a hash code value for this object.
 */
@Override
public int hashCode() {
    if (isNaN) {
        return 7;
    }
    return 37 * (17 * MathUtils.hash(imaginary) +
        MathUtils.hash(real));
}
 
Example 28
Source Project: coming   Source File: Math_47_Complex_t.java    License: MIT License 5 votes vote down vote up
/**
 * Get a hashCode for the complex number.
 * Any {@code Double.NaN} value in real or imaginary part produces
 * the same hash code {@code 7}.
 *
 * @return a hash code value for this object.
 */
@Override
public int hashCode() {
    if (isNaN) {
        return 7;
    }
    return 37 * (17 * MathUtils.hash(imaginary) +
        MathUtils.hash(real));
}
 
Example 29
Source Project: coming   Source File: Cardumen_0063_s.java    License: MIT License 5 votes vote down vote up
/**
 * Checks whether Phase 1 is solved.
 * @param tableau simple tableau for the problem
 * @return whether Phase 1 is solved
 */
private boolean isPhase1Solved(final SimplexTableau tableau) {
    if (tableau.getNumArtificialVariables() == 0) {
        return true;
    }
    for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
        if (MathUtils.compareTo(tableau.getEntry(0, i), 0, epsilon) < 0) {
            return false;
        }
    }
    return true;
}
 
Example 30
Source Project: coming   Source File: Math_87_SimplexTableau_t.java    License: MIT License 5 votes vote down vote up
/**
 * Checks whether the given column is basic.
 * @param col index of the column to check
 * @return the row that the variable is basic in.  null if the column is not basic
 */
private Integer getBasicRow(final int col) {
    Integer row = null;
    for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) {
        if (MathUtils.equals(getEntry(i, col), 1.0, epsilon) && (row == null)) {
            row = i;
        } else if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) {
            return null;
        }
    }
    return row;
}