Example usage for java.math BigInteger multiply

List of usage examples for java.math BigInteger multiply

Introduction

In this page you can find the example usage for java.math BigInteger multiply.

Prototype

BigInteger multiply(long v) 

Source Link

Document

Package private methods used by BigDecimal code to multiply a BigInteger with a long.

Usage

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*from w w w .j a  v  a  2 s .co m*/
 */
@Override
public final int initRsaPrivateKey(final ByteArray primeP, final ByteArray primeQ,
        final ByteArray primeExponentP, final ByteArray primeExponentQ, final ByteArray crtCoefficient)
        throws McbpCryptoException {
    try {
        final BigInteger p = new BigInteger(primeP.toHexString(), 16);
        final BigInteger q = new BigInteger(primeQ.toHexString(), 16);
        final BigInteger dp = new BigInteger(primeExponentP.toHexString(), 16);
        final BigInteger dq = new BigInteger(primeExponentQ.toHexString(), 16);
        final BigInteger a = new BigInteger(crtCoefficient.toHexString(), 16);

        final BigInteger n = p.multiply(q);
        final BigInteger e = dp.modInverse(p.subtract(BigInteger.ONE));

        final BigInteger d = e.modInverse(p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE))
                .divide((p.subtract(BigInteger.ONE)).gcd(q.subtract(BigInteger.ONE))));

        final RSAPrivateKey rsaKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new RSAPrivateCrtKeySpec(n, e, d, p, q, dp, dq, a));

        initRsaPrivate(rsaKey);

        return n.bitLength() / 8;

    } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:cn.iie.haiep.hbase.value.Bytes.java

/**
 * Iterate over keys within the passed inclusive range.
 */// w w  w. j  a  v a2  s . c om
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, final int num) {
    byte[] aPadded;
    byte[] bPadded;
    if (a.length < b.length) {
        aPadded = padTail(a, b.length - a.length);
        bPadded = b;
    } else if (b.length < a.length) {
        aPadded = a;
        bPadded = padTail(b, a.length - b.length);
    } else {
        aPadded = a;
        bPadded = b;
    }
    if (compareTo(aPadded, bPadded) >= 0) {
        throw new IllegalArgumentException("b <= a");
    }
    if (num <= 0) {
        throw new IllegalArgumentException("num cannot be < 0");
    }
    byte[] prependHeader = { 1, 0 };
    final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
    final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
    final BigInteger diffBI = stopBI.subtract(startBI);
    final BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    final BigInteger intervalBI;
    try {
        intervalBI = diffBI.divide(splitsBI);
    } catch (Exception e) {
        LOG.error("Exception caught during division", e);
        return null;
    }

    final Iterator<byte[]> iterator = new Iterator<byte[]>() {
        private int i = -1;

        @Override
        public boolean hasNext() {
            return i < num + 1;
        }

        @Override
        public byte[] next() {
            i++;
            if (i == 0)
                return a;
            if (i == num + 1)
                return b;

            BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
            byte[] padded = curBI.toByteArray();
            if (padded[1] == 0)
                padded = tail(padded, padded.length - 2);
            else
                padded = tail(padded, padded.length - 1);
            return padded;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

    };

    return new Iterable<byte[]>() {
        @Override
        public Iterator<byte[]> iterator() {
            return iterator;
        }
    };
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The trigonometric co-tangent.//www  .  j av  a  2 s .co m
 *
 * @param x the argument in radians.
 * @return the cot(x)
 */
static public BigDecimal cot(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) == 0) {
        throw new ArithmeticException("Cannot take cot of zero " + x.toString());
    } else if (x.compareTo(BigDecimal.ZERO) < 0) {
        return cot(x.negate()).negate();
    } else {
        /* reduce modulo pi
         */
        BigDecimal res = modpi(x);
        /* absolute error in the result is err(x)/sin^2(x) to lowest order
         */
        final double xDbl = res.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue() / 2.;
        final double eps = xUlpDbl / 2. / Math.pow(Math.sin(xDbl), 2.);
        final BigDecimal xhighpr = scalePrec(res, 2);
        final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr);
        MathContext mc = new MathContext(err2prec(xhighpr.doubleValue(), eps));
        BigDecimal resul = BigDecimal.ONE.divide(xhighpr, mc);
        /* x^(2i-1) */
        BigDecimal xpowi = xhighpr;
        Bernoulli b = new Bernoulli();
        /* 2^(2i) */
        BigInteger fourn = new BigInteger("4");
        /* (2i)! */
        BigInteger fac = BigInteger.ONE;
        for (int i = 1;; i++) {
            Rational f = b.at(2 * i);
            fac = fac.multiply(new BigInteger("" + (2 * i))).multiply(new BigInteger("" + (2 * i - 1)));
            f = f.multiply(fourn).divide(fac);
            BigDecimal c = multiplyRound(xpowi, f);
            if (i % 2 == 0) {
                resul = resul.add(c);
            } else {
                resul = resul.subtract(c);
            }
            if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                break;
            }
            fourn = fourn.shiftLeft(2);
            xpowi = multiplyRound(xpowi, xhighprSq);
        }
        mc = new MathContext(err2prec(resul.doubleValue(), eps));
        return resul.round(mc);
    }
}

From source file:com.lizardtech.expresszip.vaadin.ExportOptionsViewComponent.java

private void configureGridding() {
    GriddingOptions griddingOptions = new GriddingOptions();

    ExportProps props = getExportProps();
    griddingOptions.setExportWidth(props.getWidth());
    griddingOptions.setExportHeight(props.getHeight());

    griddingOptions.setGridding(gridCheckbox.booleanValue() && griddingDrawEnabled);

    if (griddingOptions.isGridding()) {

        if ((String) optGridOpt.getValue() == GRID_NUM_TILES) {
            griddingOptions.setGridMode(GriddingOptions.GridMode.DIVISION);

            int divX = Integer.parseInt(xTilesTextBox.getValue().toString());
            int divY = Integer.parseInt(yTilesTextBox.getValue().toString());
            griddingOptions.setDivX(divX > 0 ? divX : griddingOptions.getDivX());
            griddingOptions.setDivY(divY > 0 ? divY : griddingOptions.getDivY());

        } else { // GRID_TILE_DIMENSIONS or GRID_GROUND_DISTANCE

            griddingOptions.setGridMode(GriddingOptions.GridMode.METERS);
            if ((String) optGridOpt.getValue() == GRID_GROUND_DISTANCE) {
                Double groundResolution = getGroundResolution();
                griddingOptions.setTileSizeX((int) (Double.parseDouble(getDistance_X()) / groundResolution));
                griddingOptions.setTileSizeY((int) (Double.parseDouble(getDistance_Y()) / groundResolution));
            } else {
                griddingOptions.setTileSizeX(Integer.parseInt(getTile_X()));
                griddingOptions.setTileSizeY(Integer.parseInt(getTile_Y()));
            }//from   w  w w . j  a va2 s  . c o  m
        }
    }
    getExportProps().setGriddingOptions(griddingOptions);

    // update job summary text
    numTilesLabel.setValue(NUMBER_OF_TILES + griddingOptions.getNumTiles());

    BigInteger size = griddingOptions.getExportSize();
    String format = getImageFormat();
    if (format.equals(PNG))
        size = size.multiply(BigInteger.valueOf(85)).divide(BigInteger.valueOf(100));
    else if (format.equals(JPEG))
        size = size.divide(BigInteger.valueOf(15));
    else if (format.equals(GIF))
        size = size.multiply(BigInteger.valueOf(15)).divide(BigInteger.valueOf(100));
    else if (format.equals(BMP))
        size = size.multiply(BigInteger.valueOf(85)).divide(BigInteger.valueOf(100));
    exportSizeEstimate.setValue(DISK_ESTIMATE + FileUtils.byteCountToDisplaySize(size));
    for (ExportOptionsViewListener listener : listeners)
        listener.updateGridding(getExportProps());
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The inverse trigonometric sine./*from w  w  w  .  j a va  2s . c o  m*/
 *
 * @param x the argument.
 * @return the arcsin(x) in radians.
 */
static public BigDecimal asin(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ONE) > 0 || x.compareTo(BigDecimal.ONE.negate()) < 0) {
        throw new ArithmeticException("Out of range argument " + x.toString() + " of asin");

    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else if (x.compareTo(BigDecimal.ONE) == 0) {
        /* arcsin(1) = pi/2
         */
        double errpi = Math.sqrt(x.ulp().doubleValue());
        MathContext mc = new MathContext(err2prec(3.14159, errpi));

        return pi(mc).divide(new BigDecimal(2));

    } else if (x.compareTo(BigDecimal.ZERO) < 0) {
        return asin(x.negate()).negate();

    } else if (x.doubleValue() > 0.7) {
        final BigDecimal xCompl = BigDecimal.ONE.subtract(x);
        final double xDbl = x.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue() / 2.;
        final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.));

        final BigDecimal xhighpr = scalePrec(xCompl, 3);
        final BigDecimal xhighprV = divideRound(xhighpr, 4);
        BigDecimal resul = BigDecimal.ONE;
        /* x^(2i+1) */
        BigDecimal xpowi = BigDecimal.ONE;
        /* i factorial */
        BigInteger ifacN = BigInteger.ONE;
        BigInteger ifacD = BigInteger.ONE;

        for (int i = 1;; i++) {
            ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1)));
            ifacD = ifacD.multiply(new BigInteger("" + i));

            if (i == 1) {
                xpowi = xhighprV;
            } else {
                xpowi = multiplyRound(xpowi, xhighprV);
            }
            BigDecimal c = divideRound(multiplyRound(xpowi, ifacN),
                    ifacD.multiply(new BigInteger("" + (2 * i + 1))));
            resul = resul.add(c);
            /* series started 1+x/12+... which yields an estimate of the sums error
             */

            if (Math.abs(c.doubleValue()) < xUlpDbl / 120.) {
                break;
            }

        }
        /* sqrt(2*z)*(1+...)
         */
        xpowi = sqrt(xhighpr.multiply(new BigDecimal(2)));
        resul = multiplyRound(xpowi, resul);
        MathContext mc = new MathContext(resul.precision());
        BigDecimal pihalf = pi(mc).divide(new BigDecimal(2));
        mc = new MathContext(err2prec(resul.doubleValue(), eps));

        return pihalf.subtract(resul, mc);

    } else {
        /* absolute error in the result is err(x)/sqrt(1-x^2) to lowest order
         */
        final double xDbl = x.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue() / 2.;
        final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.));
        final BigDecimal xhighpr = scalePrec(x, 2);
        final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr);
        BigDecimal resul = xhighpr.plus();
        /* x^(2i+1) */
        BigDecimal xpowi = xhighpr;
        /* i factorial */
        BigInteger ifacN = BigInteger.ONE;
        BigInteger ifacD = BigInteger.ONE;

        for (int i = 1;; i++) {
            ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1)));
            ifacD = ifacD.multiply(new BigInteger("" + (2 * i)));
            xpowi = multiplyRound(xpowi, xhighprSq);
            BigDecimal c = divideRound(multiplyRound(xpowi, ifacN),
                    ifacD.multiply(new BigInteger("" + (2 * i + 1))));
            resul = resul.add(c);

            if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                break;
            }

        }
        MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps));

        return resul.round(mc);

    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The trigonometric tangent.//from   w  w w  .j  a  v a  2 s  .c  o m
 *
 * @param x the argument in radians.
 * @return the tan(x)
 */
static public BigDecimal tan(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else if (x.compareTo(BigDecimal.ZERO) < 0) {
        return tan(x.negate()).negate();
    } else {
        /* reduce modulo pi
         */
        BigDecimal res = modpi(x);
        /* absolute error in the result is err(x)/cos^2(x) to lowest order
         */
        final double xDbl = res.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue() / 2.;
        final double eps = xUlpDbl / 2. / Math.pow(Math.cos(xDbl), 2.);
        if (xDbl > 0.8) {
            /* tan(x) = 1/cot(x) */
            BigDecimal co = cot(x);
            MathContext mc = new MathContext(err2prec(1. / co.doubleValue(), eps));
            return BigDecimal.ONE.divide(co, mc);
        } else {
            final BigDecimal xhighpr = scalePrec(res, 2);
            final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr);
            BigDecimal resul = xhighpr.plus();
            /* x^(2i+1) */
            BigDecimal xpowi = xhighpr;
            Bernoulli b = new Bernoulli();
            /* 2^(2i) */
            BigInteger fourn = new BigInteger("4");
            /* (2i)! */
            BigInteger fac = new BigInteger("2");
            for (int i = 2;; i++) {
                Rational f = b.at(2 * i).abs();
                fourn = fourn.shiftLeft(2);
                fac = fac.multiply(new BigInteger("" + (2 * i))).multiply(new BigInteger("" + (2 * i - 1)));
                f = f.multiply(fourn).multiply(fourn.subtract(BigInteger.ONE)).divide(fac);
                xpowi = multiplyRound(xpowi, xhighprSq);
                BigDecimal c = multiplyRound(xpowi, f);
                resul = resul.add(c);
                if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                    break;
                }
            }
            MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps));
            return resul.round(mc);
        }
    }
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

/**
 * Creates space for an additional amount of nodes at the specified position in the specified node.
 *
 * @param con        an open and valid connection
 * @param seq        reference to the sequencer
 * @param mode       tree mode/*w  w  w  .j a va 2 s.co m*/
 * @param nodeId     the node to work on
 * @param position   the position within the child nodes (0 based)
 * @param additional the amount of additional nodes to make space for
 * @return the used spacing
 * @throws FxApplicationException on errors
 */
public BigInteger makeSpace(Connection con, SequencerEngine seq, FxTreeMode mode, long nodeId, int position,
        final int additional) throws FxApplicationException {
    FxTreeNodeInfoSpreaded nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, nodeId);
    BigInteger boundaries[] = getBoundaries(con, nodeInfo, position);

    int totalChildCount = nodeInfo.getTotalChildCount() + additional;
    boolean hasSpace = nodeInfo.hasSpaceFor(totalChildCount, 2);
    /*if( hasSpace )
    return nodeInfo.getSpacing(totalChildCount);*/

    // Determine node to work on
    while (!hasSpace) {
        nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, nodeInfo.getParentId());
        totalChildCount += nodeInfo.getTotalChildCount() + 1;
        hasSpace = nodeInfo.hasSpaceFor(totalChildCount, 2);
        if (!hasSpace && nodeInfo.isRoot()) {
            throw new FxUpdateException("ex.tree.makeSpace.failed");
        }
    }

    // Allocate/Reorganize space
    BigInteger spacing = nodeInfo.getSpacing(totalChildCount);
    int spaceCount = (additional * 2) + 1;
    BigInteger insertSpace = spacing.multiply(BigInteger.valueOf(spaceCount));
    insertSpace = insertSpace.add(BigInteger.valueOf(additional * 2));

    reorganizeSpace(con, seq, mode, mode, nodeInfo.getId(), false, spacing, null, nodeInfo, position,
            insertSpace, boundaries, 0, null, false, false, false);
    return spacing;
}

From source file:ch.oakmountain.tpa.solver.TrainPathAllocationProblemStatistics.java

private void compileSummaryTable() throws IOException {
    TablePersistor summaryTable = new TablePersistor("summary", outputDir, "Train Path Allocation Problem",
            getHeader());/*  w ww .ja  va2 s.  co m*/

    for (TrainPathSlot trainPathSlot : arcNodeUnitCapacityCounts.keySet()) {
        int count = arcNodeUnitCapacityCounts.get(trainPathSlot);
        arcNodeUnitCapacityConstraints += 1;
        arcNodeUnitCapacityConstraintTerms += count;
    }
    for (TrainPathSlot trainPathSlot : pathBasedConflictCounts.keySet()) {
        int count = pathBasedConflictCounts.get(trainPathSlot);
        pathBasedSolutionCandidateConflictConstraints += 1;
        pathBasedSolutionCandidateConflictTerms += count;
    }

    // arc-node
    // - flow constraints: sum of nb verticies of all DAGs (terms per constraint: nb of solution candidates)
    // - unit capacity: nb of slots of all DAGs (terms per constraint: at most one term per application)
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "feasible requests",
            String.valueOf(feasibleSimpleTrainPathApplications.size())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "infeasible requests",
            String.valueOf(infeasibleSimpleTrainPathApplications.size())));
    summaryTable.writeRow(
            Arrays.asList("arc-node/path-based", "total number of train paths", String.valueOf(totalNbPaths)));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global minimum dwell time",
            PeriodicalTimeFrame.formatDuration(
                    feasibleSimpleTrainPathApplications.get(0).getParams().getHARD_MINIMUM_DWELL_TIME())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global maximum earlier departure time",
            PeriodicalTimeFrame.formatDuration(feasibleSimpleTrainPathApplications.get(0).getParams()
                    .getHARD_MAXIMUM_EARLIER_DEPARTURE())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global maximum later arrival time",
            PeriodicalTimeFrame.formatDuration(
                    feasibleSimpleTrainPathApplications.get(0).getParams().getHARD_MAXIMUM_LATER_ARRIVAL())));

    summaryTable.writeRow(
            Arrays.asList("arc-node", "flow constraints", String.valueOf(arcNodeFlowConstraintsCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "terms in flow constraints",
            String.valueOf(arcNodeFlowConstraintTermsCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraints)));
    summaryTable.writeRow(Arrays.asList("arc-node", "terms in unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraintTerms)));
    BigInteger arcNodeConstraints = BigInteger
            .valueOf(arcNodeFlowConstraintsCount + arcNodeUnitCapacityConstraints);
    summaryTable.writeRow(Arrays.asList("arc-node", "rows (constraints)", String.valueOf(arcNodeConstraints)));
    summaryTable
            .writeRow(Arrays.asList("arc-node", "columns (variables)", String.valueOf(arcNodeVariablesCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "train path slots",
            String.valueOf(arcNodeUnitCapacityCounts.keySet().size())));
    BigInteger arcNodeTerms = BigInteger
            .valueOf(arcNodeFlowConstraintTermsCount + arcNodeUnitCapacityConstraintTerms);
    BigInteger arcNodeFlowConstraintMatrixSize = BigInteger.valueOf(arcNodeFlowConstraintTermsCount)
            .multiply(BigInteger.valueOf(arcNodeVariablesCount));
    BigInteger arcNodeUnitCapacityConstraintMatrixSize = BigInteger.valueOf(arcNodeUnitCapacityConstraintTerms)
            .multiply(BigInteger.valueOf(arcNodeVariablesCount));
    BigInteger arcNodeMatrixSize = arcNodeConstraints.multiply(BigInteger.valueOf(arcNodeVariablesCount));
    summaryTable.writeRow(Arrays.asList("arc-node", "sparsity in flow constraints",
            String.valueOf(arcNodeFlowConstraintTermsCount + "/" + arcNodeFlowConstraintMatrixSize + " ("
                    + (new BigDecimal(arcNodeFlowConstraintTermsCount))
                            .divide((new BigDecimal(arcNodeFlowConstraintMatrixSize)), 10, RoundingMode.HALF_UP)
                    + ")")));
    summaryTable.writeRow(Arrays.asList("arc-node", "sparsity in unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraintTerms + "/" + arcNodeUnitCapacityConstraintMatrixSize
                    + " ("
                    + (new BigDecimal(arcNodeUnitCapacityConstraintTerms)).divide(
                            (new BigDecimal(arcNodeUnitCapacityConstraintMatrixSize)), 10, RoundingMode.HALF_UP)
                    + ")")));
    summaryTable
            .writeRow(
                    Arrays.asList("arc-node", "sparsity in all constraints",
                            String.valueOf(arcNodeTerms
                                    + "/" + arcNodeMatrixSize + " (" + (new BigDecimal(arcNodeTerms))
                                            .divide(new BigDecimal(arcNodeMatrixSize), 10, RoundingMode.HALF_UP)
                                    + ")")));

    // path-based
    // - solution candidate choice: nb of applications (terms per constraint: nb of solution canidates)
    // - conflict sets: nb of slots of all DAGs (terms per constraint: possibly many terms per application)
    summaryTable.writeRow(Arrays.asList("path-based", "choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "terms in choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictConstraints)));
    summaryTable.writeRow(Arrays.asList("path-based", "terms in conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictTerms)));
    summaryTable.writeRow(Arrays.asList("path-based", "enumeration rate ",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount + "/" + totalNbPaths + "("
                    + ((double) pathBasedSolutionCandidateChoiceTermsCount / totalNbPaths) + ")")));
    BigInteger pathBasedConstraints = BigInteger.valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)
            .add(BigInteger.valueOf(pathBasedSolutionCandidateConflictConstraints));
    summaryTable
            .writeRow(Arrays.asList("path-based", "rows (constraints)", String.valueOf(pathBasedConstraints)));
    summaryTable.writeRow(
            Arrays.asList("path-based", "columns (variables)", String.valueOf(pathBasedVariablesCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "train path slots",
            String.valueOf(pathBasedConflictCounts.keySet().size())));
    BigInteger pathBasedTerms = BigInteger.valueOf(pathBasedSolutionCandidateConflictTerms)
            .add(BigInteger.valueOf(pathBasedSolutionCandidateChoiceTermsCount));
    BigInteger pathBasedMatrixSize = pathBasedConstraints.multiply(BigInteger.valueOf(pathBasedVariablesCount));
    BigInteger pathBasedSolutionCandidateChoiceMatrixSize = BigInteger
            .valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)
            .multiply(BigInteger.valueOf(pathBasedVariablesCount));
    BigInteger pathBasedSolutionCandidateConflictMatrixSize = BigInteger
            .valueOf(pathBasedSolutionCandidateConflictConstraints)
            .multiply(BigInteger.valueOf(pathBasedVariablesCount));
    summaryTable.writeRow(Arrays.asList("path-based", "sparsity in choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount + "/"
                    + pathBasedSolutionCandidateChoiceMatrixSize + " ("
                    + (new BigDecimal(pathBasedSolutionCandidateChoiceTermsCount)).divide(
                            new BigDecimal(pathBasedSolutionCandidateChoiceMatrixSize), 10,
                            RoundingMode.HALF_UP)
                    + ")")));
    summaryTable.writeRow(Arrays.asList("path-based", "sparsity in conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictTerms + "/"
                    + pathBasedSolutionCandidateConflictMatrixSize + " ("
                    + (new BigDecimal(pathBasedSolutionCandidateConflictTerms)).divide(
                            (new BigDecimal(pathBasedSolutionCandidateConflictMatrixSize)), 10,
                            RoundingMode.HALF_UP)
                    + ")")));
    summaryTable
            .writeRow(
                    Arrays.asList("path-based", "sparsity in all constraints",
                            String.valueOf(pathBasedTerms + "/" + pathBasedMatrixSize + " ("
                                    + (new BigDecimal(pathBasedTerms)).divide(
                                            (new BigDecimal(pathBasedMatrixSize)), 10, RoundingMode.HALF_UP)
                                    + ")")));

    summaryTable.finishTable();

    if (!(arcNodeUnitCapacityCounts.keySet().size() >= pathBasedConflictCounts.keySet().size())) {
        throw new IllegalStateException(
                "nb of train path slots in arc node model has to be larger or equal to the number of train path slots in the path based model (because of partial enumeration)");
    }

    // LaTeX table output
    DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance();
    //DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();

    //symbols.setGroupingSeparator(' ');
    //formatter.setDecimalFormatSymbols(symbols);
    File latexFile = new File(outputDir + File.separator + "computational.tex");
    FileUtils.writeStringToFile(latexFile, "Number of feasible applications:&\\multicolumn{2}{c|}{"
            + formatter.format(feasibleSimpleTrainPathApplications.size()) + "}\\\\\n");
    FileUtils.writeStringToFile(latexFile,
            "Number of variables      &" + formatter.format(arcNodeVariablesCount) + "&"
                    + formatter.format(pathBasedVariablesCount) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "Number of constraints   &" + formatter.format(arcNodeConstraints)
            + "&" + formatter.format(pathBasedConstraints) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of unit capacity / conflict constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&" + formatter.format(arcNodeUnitCapacityConstraints)
                    + "                                         &"
                    + formatter.format(pathBasedSolutionCandidateConflictConstraints) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "%    Matrix size                     &"
            + formatter.format(arcNodeMatrixSize) + "&" + formatter.format(pathBasedMatrixSize) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "%Number of terms           &" + formatter.format(arcNodeTerms) + "&"
            + formatter.format(pathBasedTerms) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of terms in unit capacity/", true);
    FileUtils.writeStringToFile(latexFile,
            "&" + formatter.format(arcNodeUnitCapacityConstraintTerms) + "& \\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "\\hspace{0.5cm}choice constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&&" + formatter.format(pathBasedSolutionCandidateChoiceTermsCount) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of terms in flow conservation/", true);
    FileUtils.writeStringToFile(latexFile, "&" + formatter.format(arcNodeFlowConstraintTermsCount) + "& \\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "\\hspace{0.5cm}conflict constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&&" + formatter.format(pathBasedSolutionCandidateConflictTerms) + "\\\\\n", true);
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

protected long _reorganizeSpace(Connection con, SequencerEngine seq, FxTreeMode sourceMode, FxTreeMode destMode,
        long nodeId, boolean includeNodeId, BigInteger overrideSpacing, BigInteger overrideLeft,
        FxTreeNodeInfo insertParent, int insertPosition, BigInteger insertSpace, BigInteger insertBoundaries[],
        int depthDelta, Long destinationNode, boolean createMode, boolean createKeepIds,
        boolean disableSpaceOptimization) throws FxTreeException {
    long firstCreatedNodeId = -1;
    FxTreeNodeInfoSpreaded nodeInfo;/* ww w  .j  a  va2  s .c om*/
    try {
        nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, sourceMode, nodeId);
    } catch (Exception e) {
        return -1;
    }

    if (!nodeInfo.isSpaceOptimizable() && !disableSpaceOptimization) {
        // The Root node and cant be optimize any more ... so all we can do is fail :-/
        // This should never really happen
        if (nodeId == ROOT_NODE) {
            return -1;
        }
        //System.out.println("### UP we go, depthDelta=" + depthDelta);
        return _reorganizeSpace(con, seq, sourceMode, destMode, nodeInfo.getParentId(), includeNodeId,
                overrideSpacing, overrideLeft, insertParent, insertPosition, insertSpace, insertBoundaries,
                depthDelta, destinationNode, createMode, createKeepIds, false);
    }

    BigInteger spacing = nodeInfo.getDefaultSpacing();
    if (overrideSpacing != null && (overrideSpacing.compareTo(spacing) < 0 || overrideLeft != null)) {
        // override spacing unless it is greater OR overrideLeft is specified (in that case we
        // have to use the spacing for valid tree ranges)  
        spacing = overrideSpacing;
    } else {
        if (spacing.compareTo(GO_UP) < 0 && !createMode && !disableSpaceOptimization) {
            return _reorganizeSpace(con, seq, sourceMode, destMode, nodeInfo.getParentId(), includeNodeId,
                    overrideSpacing, overrideLeft, insertParent, insertPosition, insertSpace, insertBoundaries,
                    depthDelta, destinationNode, createMode, createKeepIds, false);
        }
    }

    if (insertBoundaries != null && insertPosition == -1) {
        insertPosition = 0; // insertPosition cannot be negative
    }

    Statement stmt = null;
    PreparedStatement ps = null;
    ResultSet rs;
    BigInteger left = overrideLeft == null ? nodeInfo.getLeft() : overrideLeft;
    BigInteger right = null;
    String includeNode = includeNodeId ? "=" : "";
    long counter = 0;
    long newId = -1;
    try {
        final long start = System.currentTimeMillis();
        String createProps = createMode ? ",PARENT,REF,NAME,TEMPLATE" : "";
        String sql = " SELECT ID," + StorageManager.getIfFunction( // compute total child count only when the node has children
                "CHILDCOUNT = 0", "0",
                "(SELECT COUNT(*) FROM " + getTable(sourceMode) + " WHERE LFT > NODE.LFT AND RGT < NODE.RGT)") +
        // 3           4             5   6
                ", CHILDCOUNT, LFT AS LFTORD,RGT,DEPTH" + createProps
                + " FROM (SELECT ID,CHILDCOUNT,LFT,RGT,DEPTH" + createProps + " FROM " + getTable(sourceMode)
                + " WHERE " + "LFT>" + includeNode + nodeInfo.getLeft() + " AND LFT<" + includeNode
                + nodeInfo.getRight() + ") NODE " + "ORDER BY LFTORD ASC";
        stmt = con.createStatement();
        rs = stmt.executeQuery(sql);
        if (createMode) {
            //                                                                 1  2      3     4     5   6        7   8
            ps = con.prepareStatement(
                    "INSERT INTO " + getTable(destMode) + " (ID,PARENT,DEPTH,DIRTY,REF,TEMPLATE,LFT,RGT," +
                    //9           10    11
                            "CHILDCOUNT,NAME,MODIFIED_AT) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?)");
        } else {
            ps = con.prepareStatement("UPDATE " + getTable(sourceMode) + " SET LFT=?,RGT=?,DEPTH=? WHERE ID=?");
        }
        long id;
        int total_childs;
        int direct_childs;
        BigInteger nextLeft;
        int lastDepth = nodeInfo.getDepth() + (includeNodeId ? 0 : 1);
        int depth;
        BigInteger _rgt;
        BigInteger _lft;
        Long ref = null;
        String data = null;
        String name = "";

        Stack<Long> currentParent = null;
        if (createMode) {
            currentParent = new Stack<Long>();
            currentParent.push(destinationNode);
        }

        //System.out.println("Spacing:"+SPACING);
        while (rs.next()) {
            //System.out.println("------------------");
            id = rs.getLong(1);
            total_childs = rs.getInt(2);
            direct_childs = rs.getInt(3);
            _lft = getNodeBounds(rs, 4);
            _rgt = getNodeBounds(rs, 5);
            depth = rs.getInt(6);
            if (createMode) {
                // Reading these properties is slow, only do it when needed
                ref = rs.getLong(8);
                if (rs.wasNull())
                    ref = null;
                name = rs.getString(9);
                data = rs.getString(10);
                if (rs.wasNull())
                    data = null;
            }
            left = left.add(spacing).add(BigInteger.ONE);

            // Handle depth differences
            if (lastDepth - depth > 0) {
                BigInteger depthDifference = spacing.add(BigInteger.ONE);
                left = left.add(depthDifference.multiply(BigInteger.valueOf(lastDepth - depth)));
            }
            if (createMode) {
                if (lastDepth < depth) {
                    currentParent.push(newId);
                } else if (lastDepth > depth) {
                    for (int p = 0; p < (lastDepth - depth); p++)
                        currentParent.pop();
                }
            }

            right = left.add(spacing).add(BigInteger.ONE);

            // add child space if needed
            if (total_childs > 0) {
                BigInteger childSpace = spacing.multiply(BigInteger.valueOf(total_childs * 2));
                childSpace = childSpace.add(BigInteger.valueOf((total_childs * 2) - 1));
                right = right.add(childSpace);
                nextLeft = left;
            } else {
                nextLeft = right;
            }

            if (insertBoundaries != null) {
                // insert gap at requested position
                // If we're past the gap, keep adding the insert space to left/right because the added
                // space is never "injected" into the loop, i.e. without adding it the left/right boundaries of
                // nodes after the gap would be too far to the left.
                if (_lft.compareTo(insertBoundaries[0]) > 0) {
                    left = left.add(insertSpace);
                }
                if (_rgt.compareTo(insertBoundaries[0]) > 0) {
                    right = right.add(insertSpace);
                }
            }

            // sanity checks
            if (left.compareTo(right) >= 0) {
                throw new FxTreeException(LOG, "ex.tree.reorganize.failed", counter, left, right,
                        "left greater than right");
            }
            if (insertParent != null && right.compareTo((BigInteger) insertParent.getRight()) > 0) {
                throw new FxTreeException(LOG, "ex.tree.reorganize.failed", counter, left, right,
                        "wrote past parent node bounds");
            }

            // Update the node
            if (createMode) {
                newId = createKeepIds ? id : seq.getId(destMode.getSequencer());
                if (firstCreatedNodeId == -1)
                    firstCreatedNodeId = newId;

                // Create the main entry
                ps.setLong(1, newId);
                ps.setLong(2, currentParent.peek());
                ps.setLong(3, depth + depthDelta);
                ps.setBoolean(4, destMode != FxTreeMode.Live); //only flag non-live tree's dirty
                if (ref == null) {
                    ps.setNull(5, java.sql.Types.NUMERIC);
                } else {
                    ps.setLong(5, ref);
                }
                if (data == null) {
                    ps.setNull(6, java.sql.Types.VARCHAR);
                } else {
                    ps.setString(6, data);
                }
                //                    System.out.println("=> id:"+newId+" left:"+left+" right:"+right);
                setNodeBounds(ps, 7, left);
                setNodeBounds(ps, 8, right);
                ps.setInt(9, direct_childs);
                ps.setString(10, name);
                ps.setLong(11, System.currentTimeMillis());
                ps.addBatch();
            } else {
                setNodeBounds(ps, 1, left);
                setNodeBounds(ps, 2, right);
                ps.setInt(3, depth + depthDelta);
                ps.setLong(4, id);
                ps.addBatch();
                //                    ps.executeBatch();
                //                    ps.clearBatch();
            }

            // Prepare variables for the next node
            left = nextLeft;
            lastDepth = depth;
            counter++;

            // Execute batch every 10000 items to avoid out of memory
            if (counter % 10000 == 0) {
                ps.executeBatch();
                ps.clearBatch();
            }
        }
        rs.close();
        stmt.close();
        stmt = null;
        ps.executeBatch();

        if (LOG.isDebugEnabled()) {
            final long time = System.currentTimeMillis() - start;

            LOG.debug("Tree reorganization of " + counter + " items completed in " + time + " ms (spaceLen="
                    + spacing + ")");
        }
        return firstCreatedNodeId;
    } catch (FxApplicationException e) {
        throw e instanceof FxTreeException ? (FxTreeException) e : new FxTreeException(e);
    } catch (SQLException e) {
        String next = "";
        if (e.getNextException() != null)
            next = " next:" + e.getNextException().getMessage();
        if (StorageManager.isDuplicateKeyViolation(e))
            throw new FxTreeException(LOG, e, "ex.tree.reorganize.duplicateKey");
        throw new FxTreeException(LOG, e, "ex.tree.reorganize.failed", counter, left, right,
                e.getMessage() + next);
    } catch (Exception e) {
        throw new FxTreeException(e);
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (Throwable t) {
            /*ignore*/}
        try {
            if (ps != null)
                ps.close();
        } catch (Throwable t) {
            /*ignore*/}
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The exponential function.//from  w  ww. j a  v  a  2 s  .  c o m
 *
 * @param x the argument.
 * @return exp(x).
 * The precision of the result is implicitly defined by the precision in the argument.
 * 16
 * In particular this means that "Invalid Operation" errors are thrown if catastrophic
 * cancellation of digits causes the result to have no valid digits left.
 */
static public BigDecimal exp(BigDecimal x) {
    /* To calculate the value if x is negative, use exp(-x) = 1/exp(x)
     */
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        final BigDecimal invx = exp(x.negate());
        /* Relative error in inverse of invx is the same as the relative errror in invx.
         * This is used to define the precision of the result.
         */
        MathContext mc = new MathContext(invx.precision());
        return BigDecimal.ONE.divide(invx, mc);
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        /* recover the valid number of digits from x.ulp(), if x hits the
         * zero. The x.precision() is 1 then, and does not provide this information.
         */
        return scalePrec(BigDecimal.ONE, -(int) (Math.log10(x.ulp().doubleValue())));
    } else {
        /* Push the number in the Taylor expansion down to a small
         * value where TAYLOR_NTERM terms will do. If x<1, the n-th term is of the order
         * x^n/n!, and equal to both the absolute and relative error of the result
         * since the result is close to 1. The x.ulp() sets the relative and absolute error
         * of the result, as estimated from the first Taylor term.
         * We want x^TAYLOR_NTERM/TAYLOR_NTERM! < x.ulp, which is guaranteed if
         * x^TAYLOR_NTERM < TAYLOR_NTERM*(TAYLOR_NTERM-1)*...*x.ulp.
         */
        final double xDbl = x.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue();
        if (Math.pow(xDbl, TAYLOR_NTERM) < TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0)
                * xUlpDbl) {
            /* Add TAYLOR_NTERM terms of the Taylor expansion (Eulers sum formula)
             */
            BigDecimal resul = BigDecimal.ONE;
            /* x^i */
            BigDecimal xpowi = BigDecimal.ONE;
            /* i factorial */
            BigInteger ifac = BigInteger.ONE;
            /* TAYLOR_NTERM terms to be added means we move x.ulp() to the right
             * for each power of 10 in TAYLOR_NTERM, so the addition wont add noise beyond
             * whats already in x.
             */
            MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / TAYLOR_NTERM));
            for (int i = 1; i <= TAYLOR_NTERM; i++) {
                ifac = ifac.multiply(new BigInteger("" + i));
                xpowi = xpowi.multiply(x);
                final BigDecimal c = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(c);
                if (Math.abs(xpowi.doubleValue()) < i && Math.abs(c.doubleValue()) < 0.5 * xUlpDbl) {
                    break;
                }
            }
            /* exp(x+deltax) = exp(x)(1+deltax) if deltax is <<1. So the relative error
             * in the result equals the absolute error in the argument.
             */
            MathContext mc = new MathContext(err2prec(xUlpDbl / 2.));
            return resul.round(mc);
        } else {
            /* Compute exp(x) = (exp(0.1*x))^10. Division by 10 does not lead
             * to loss of accuracy.
             */
            int exSc = (int) (1.0 - Math.log10(TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0)
                    * xUlpDbl / Math.pow(xDbl, TAYLOR_NTERM)) / (TAYLOR_NTERM - 1.0));
            BigDecimal xby10 = x.scaleByPowerOfTen(-exSc);
            BigDecimal expxby10 = exp(xby10);
            /* Final powering by 10 means that the relative error of the result
             * is 10 times the relative error of the base (First order binomial expansion).
             * This looses one digit.
             */
            MathContext mc = new MathContext(expxby10.precision() - exSc);
            /* Rescaling the powers of 10 is done in chunks of a maximum of 8 to avoid an invalid operation
            17
             * response by the BigDecimal.pow library or integer overflow.
             */
            while (exSc > 0) {
                int exsub = Math.min(8, exSc);
                exSc -= exsub;
                MathContext mctmp = new MathContext(expxby10.precision() - exsub + 2);
                int pex = 1;
                while (exsub-- > 0) {
                    pex *= 10;
                }
                expxby10 = expxby10.pow(pex, mctmp);
            }
            return expxby10.round(mc);
        }
    }
}