Example usage for org.apache.commons.math3.fraction BigFraction ONE

List of usage examples for org.apache.commons.math3.fraction BigFraction ONE

Introduction

In this page you can find the example usage for org.apache.commons.math3.fraction BigFraction ONE.

Prototype

BigFraction ONE

To view the source code for org.apache.commons.math3.fraction BigFraction ONE.

Click Source Link

Document

A fraction representing "1".

Usage

From source file:model.LP.java

/**
 * Do one iteration of the simplex method.
 *
 * @param  entering/*from  www  . j  a  v a2s.co  m*/
 *         Index of variable to enter the basis.
 * @param  leaving
 *         Index of variable to leave the basis.
 * @return
 *         A linear program after one iteration.
 */
public LP pivot(int entering, int leaving) {
    FieldMatrix<BigFraction> bin = new FieldLUDecomposition<BigFraction>(B_).getSolver().getInverse()
            .multiply(N_);

    // Step 1: Check for optimpivality
    // Step 2: Select entering variable.
    // Naive method. Does not check for optimality. Assumes feasibility.
    // Entering variable is given.

    // Step 3: Compute primal step direction.
    FieldVector<BigFraction> ej = new ArrayFieldVector<BigFraction>(bin.getColumnDimension(), BigFraction.ZERO);
    ej.setEntry(entering, BigFraction.ONE);
    FieldVector<BigFraction> psd = bin.operate(ej);

    // Step 4: Compute primal step length.
    // Step 5: Select leaving variable.
    // Leaving variable is given.
    BigFraction t = b_.getEntry(leaving).divide(psd.getEntry(leaving));

    // Step 6: Compute dual step direction.
    FieldVector<BigFraction> ei = new ArrayFieldVector<BigFraction>(bin.getRowDimension(), BigFraction.ZERO);
    ei.setEntry(leaving, BigFraction.ONE);
    FieldVector<BigFraction> dsd = bin.transpose().scalarMultiply(BigFraction.MINUS_ONE).operate(ei);

    // Step 7: Compute dual step length.
    BigFraction s = c_.getEntry(entering).divide(dsd.getEntry(entering));

    // Step 8: Update current primal and dual solutions.
    FieldVector<BigFraction> nb_ = b_.subtract(psd.mapMultiply(t));
    nb_.setEntry(leaving, t);

    FieldVector<BigFraction> nc_ = c_.subtract(dsd.mapMultiply(s));
    nc_.setEntry(entering, s);

    // Step 9: Update basis.
    FieldVector<BigFraction> temp = B_.getColumnVector(leaving);
    FieldMatrix<BigFraction> nB_ = B_.copy();
    nB_.setColumn(leaving, N_.getColumn(entering));

    FieldMatrix<BigFraction> nN_ = N_.copy();
    nN_.setColumnVector(entering, temp);

    int[] nBi = Bi.clone();
    int[] nNi = Ni.clone();
    nBi[leaving] = Ni[entering];
    nNi[entering] = Bi[leaving];

    return new LP(B, N, b, c, nB_, nN_, nb_, nc_, x, nBi, nNi);
}

From source file:cc.redberry.core.number.Complex.java

@Override
public Complex multiply(BigFraction fraction) {
    return fraction.compareTo(BigFraction.ONE) == 0 ? this
            : new Complex(real.multiply(fraction), imaginary.multiply(fraction));
}

From source file:cc.redberry.core.number.Complex.java

@Override
public Complex divide(BigFraction fraction) {
    return fraction.compareTo(BigFraction.ONE) == 0 ? this
            : new Complex(real.divide(fraction), imaginary.divide(fraction));
}

From source file:cz.cuni.mff.spl.evaluator.statistics.KolmogorovSmirnovTestFlag.java

/***
 * Creates {@code H} of size {@code m x m} as described in [1] (see above).
 *
 * @param d statistic/*from   ww  w .  ja  v  a2s  . c o m*/
 * @param n sample size
 * @return H matrix
 * @throws NumberIsTooLargeException if fractional part is greater than 1
 * @throws FractionConversionException if algorithm fails to convert {@code h} to a
 *         {@link org.apache.commons.math3.fraction.BigFraction} in expressing {@code d} as \((k
 *         - h) / m\) for integer {@code k, m} and \(0 <= h < 1\).
 */
private FieldMatrix<BigFraction> createExactH(double d, int n)
        throws NumberIsTooLargeException, FractionConversionException {

    final int k = (int) Math.ceil(n * d);
    final int m = 2 * k - 1;
    final double hDouble = k - n * d;
    if (hDouble >= 1) {
        throw new NumberIsTooLargeException(hDouble, 1.0, false);
    }
    BigFraction h = null;
    try {
        h = new BigFraction(hDouble, 1.0e-20, 10000);
    } catch (final FractionConversionException e1) {
        try {
            h = new BigFraction(hDouble, 1.0e-10, 10000);
        } catch (final FractionConversionException e2) {
            h = new BigFraction(hDouble, 1.0e-5, 10000);
        }
    }
    final BigFraction[][] Hdata = new BigFraction[m][m];

    /*
     * Start by filling everything with either 0 or 1.
     */
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < m; ++j) {
            if (i - j + 1 < 0) {
                Hdata[i][j] = BigFraction.ZERO;
            } else {
                Hdata[i][j] = BigFraction.ONE;
            }
        }
    }

    /*
     * Setting up power-array to avoid calculating the same value twice: hPowers[0] = h^1 ...
     * hPowers[m-1] = h^m
     */
    final BigFraction[] hPowers = new BigFraction[m];
    hPowers[0] = h;
    for (int i = 1; i < m; ++i) {
        hPowers[i] = h.multiply(hPowers[i - 1]);
    }

    /*
     * First column and last row has special values (each other reversed).
     */
    for (int i = 0; i < m; ++i) {
        Hdata[i][0] = Hdata[i][0].subtract(hPowers[i]);
        Hdata[m - 1][i] = Hdata[m - 1][i].subtract(hPowers[m - i - 1]);
    }

    /*
     * [1] states: "For 1/2 < h < 1 the bottom left element of the matrix should be (1 - 2*h^m +
     * (2h - 1)^m )/m!" Since 0 <= h < 1, then if h > 1/2 is sufficient to check:
     */
    if (h.compareTo(BigFraction.ONE_HALF) == 1) {
        Hdata[m - 1][0] = Hdata[m - 1][0].add(h.multiply(2).subtract(1).pow(m));
    }

    /*
     * Aside from the first column and last row, the (i, j)-th element is 1/(i - j + 1)! if i -
     * j + 1 >= 0, else 0. 1's and 0's are already put, so only division with (i - j + 1)! is
     * needed in the elements that have 1's. There is no need to calculate (i - j + 1)! and then
     * divide - small steps avoid overflows. Note that i - j + 1 > 0 <=> i + 1 > j instead of
     * j'ing all the way to m. Also note that it is started at g = 2 because dividing by 1 isn't
     * really necessary.
     */
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < i + 1; ++j) {
            if (i - j + 1 > 0) {
                for (int g = 2; g <= i - j + 1; ++g) {
                    Hdata[i][j] = Hdata[i][j].divide(g);
                }
            }
        }
    }
    return new Array2DRowFieldMatrix<BigFraction>(BigFractionField.getInstance(), Hdata);
}

From source file:sadl.models.PDFA.java

protected boolean fixProbability(int state) {
    List<Transition> outgoingTransitions = getOutTransitions(state, true);
    final double sum = outgoingTransitions.stream().mapToDouble(t -> t.getProbability()).sum();
    // divide every probability by the sum of probabilities s.t. they sum up to 1
    if (!Precision.equals(sum, 1)) {
        logger.debug("Sum of transition probabilities for state {} is {}", state, sum);
        outgoingTransitions = getOutTransitions(state, true);
        outgoingTransitions.forEach(t -> changeTransitionProbability(t, t.getProbability() / sum));
        outgoingTransitions = getOutTransitions(state, true);
        final double newSum = outgoingTransitions.stream().mapToDouble(t -> t.getProbability()).sum();
        logger.debug("Corrected sum of transition probabilities is {}", newSum);
        if (!Precision.equals(newSum, 1.0)) {
            logger.debug("Probabilities do not sum up to one, so doing it again with the Fraction class");
            final List<BigFraction> probabilities = new ArrayList<>(outgoingTransitions.size());
            for (int i = 0; i < outgoingTransitions.size(); i++) {
                probabilities.add(i, new BigFraction(outgoingTransitions.get(i).getProbability()));
            }//w ww  . j a  v a 2  s .  c o m
            BigFraction fracSum = BigFraction.ZERO;
            for (final BigFraction f : probabilities) {
                try {
                    fracSum = fracSum.add(f);
                } catch (final MathArithmeticException e) {
                    logger.error("Arithmetic Exception for fracSum={}, FractionToAdd={}", fracSum, f, e);
                    throw e;
                }
            }
            for (int i = 0; i < outgoingTransitions.size(); i++) {
                changeTransitionProbability(outgoingTransitions.get(i),
                        probabilities.get(i).divide(fracSum).doubleValue());
                // outgoingTransitions.get(i).setProbability(probabilities.get(i).divide(fracSum).doubleValue());
            }
            final double tempSum = getOutTransitions(state, true).stream().mapToDouble(t -> t.getProbability())
                    .sum();
            if (!Precision.equals(tempSum, 1.0)) {
                BigFraction preciseSum = BigFraction.ZERO;
                for (final BigFraction f : probabilities) {
                    preciseSum = preciseSum.add(f.divide(fracSum));
                }
                if (!preciseSum.equals(BigFraction.ONE)) {
                    throw new IllegalStateException(
                            "Probabilities do not sum up to one, but instead to " + tempSum);
                } else {
                    logger.warn(
                            "Probabilities do not sum up to one, but instead to {}. This is due to double underflows, but they sum up to one if using BigFraction. This small error will be ignored.",
                            tempSum);
                }
            }
        }
    }
    return true;
}