Example usage for java.math BigDecimal max

List of usage examples for java.math BigDecimal max

Introduction

In this page you can find the example usage for java.math BigDecimal max.

Prototype

public BigDecimal max(BigDecimal val) 

Source Link

Document

Returns the maximum of this BigDecimal and val .

Usage

From source file:Main.java

public static void main(String[] args) {

    BigDecimal bg1 = new BigDecimal("123");
    BigDecimal bg2 = new BigDecimal("456");

    // assign the max value of bg1, bg2 to bg3
    BigDecimal bg3 = bg1.max(bg2);

    System.out.println(bg3);/*  w w  w.  j a  v  a 2  s  .c o  m*/
}

From source file:MainClass.java

public static void main(String argv[]) {
    BigDecimal first = new BigDecimal("3419229223372036854775807.23343");
    BigDecimal second = new BigDecimal("2.0");
    System.out.println(first.add(second));
    System.out.println(first.subtract(second));
    System.out.println(first.divide(second));
    System.out.println(first.equals(second));
    System.out.println(first.abs());
    System.out.println(first.max(second));
    System.out.println(first.min(second));
    System.out.println(first.remainder(second));
}

From source file:Main.java

public static double returnMax(double v1, double v2) {
    BigDecimal b1 = new BigDecimal(v1);
    BigDecimal b2 = new BigDecimal(v2);
    return b1.max(b2).doubleValue();
}

From source file:com.jsquant.servlet.YahooFinanceProxyCalc.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /* http://ichart.finance.yahoo.com/table.csv?a=00&c=2005&b=01&e=03&d=05&g=d&f=2008&ignore=.csv&s=GOOG
    Date,Open,High,Low,Close,Volume,Adj Close
    2008-06-03,576.50,580.50,560.61,567.30,4305300,567.30
    2008-06-02,582.50,583.89,571.27,575.00,3674200,575.00
    *///  ww  w . ja v a  2  s .c  o  m
    int fromMM = Integer.valueOf(request.getParameter("a")); // 00 == January
    int fromDD = Integer.valueOf(request.getParameter("b"));
    int fromYYYY = Integer.valueOf(request.getParameter("c"));
    int toMM = Integer.valueOf(request.getParameter("d"));
    int toDD = Integer.valueOf(request.getParameter("e"));
    int toYYYY = Integer.valueOf(request.getParameter("f"));
    String resolution = request.getParameter("g").substring(0, 1); // == "d"ay "w"eek "m"onth "y"ear
    ValidationUtils.validateResolution(resolution);
    String symbol = request.getParameter("s");
    ValidationUtils.validateSymbol(symbol);
    String queryString = String.format("a=%02d&b=%02d&c=%d&d=%02d&e=%02d&f=%d&g=%s&s=%s&ignore=.csv", fromMM,
            fromDD, fromYYYY, toMM, toDD, toYYYY,
            URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING),
            URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING));
    String cacheKey = String.format("%02d%02d%d-%02d%02d%d-%s-%s-%tF-calc.csv.gz", fromMM, fromDD, fromYYYY,
            toMM, toDD, toYYYY,
            URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING),
            URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), new Date()); // include server date to limit to 1 day, for case where future dates might return less data, but fill cache

    FileCache fileCache = JsquantContextListener.getFileCache(request);
    String responseBody = fileCache.get(cacheKey);
    if (responseBody == null) {
        HttpGet httpget = new HttpGet("http://ichart.finance.yahoo.com/table.csv?" + queryString);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        log.debug("requesting uri=" + httpget.getURI());
        responseBody = JsquantContextListener.getHttpClient(request).execute(httpget, responseHandler);
        //httpget.setReleaseTrigger(releaseTrigger); // no need to close?
        fileCache.put(cacheKey, responseBody);
    }

    String[] lines = responseBody.split("\n");
    List<Stock> dayPrices = new ArrayList<Stock>();
    int index = 0;
    for (String line : lines)
        if (index++ > 0 && line.length() > 0)
            dayPrices.add(new Stock(line));
    Collections.reverse(dayPrices);

    index = 0;
    BigDecimal allTimeHighClose = new BigDecimal(0);
    BigDecimal stopAt = null;
    BigDecimal boughtPrice = null;
    Stock sPrev = null;
    for (Stock s : dayPrices) {
        allTimeHighClose = allTimeHighClose.max(s.adjClose);
        s.allTimeHighClose = allTimeHighClose;
        if (index > 0) {
            sPrev = dayPrices.get(index - 1);
            //true range = max(high,closeprev) - min(low,closeprev)
            s.trueRange = s.high.max(sPrev.adjClose).subtract(s.low.min(sPrev.adjClose));
        }
        int rng = 10;
        if (index > rng) {
            BigDecimal sum = new BigDecimal(0);
            for (Stock s2 : dayPrices.subList(index - rng, index))
                sum = sum.add(s2.trueRange);
            s.ATR10 = sum.divide(new BigDecimal(rng));

            if (allTimeHighClose.equals(s.adjClose)) {
                stopAt = s.adjClose.subtract(s.ATR10);
            }
        }

        s.stopAt = stopAt;

        if (s.stopAt != null && s.adjClose.compareTo(s.stopAt) == -1 && sPrev != null
                && (sPrev.order == OrderAction.BUY || sPrev.order == OrderAction.HOLD)) {
            s.order = OrderAction.SELL;
            s.soldPrice = s.adjClose;
            s.soldDifference = s.soldPrice.subtract(boughtPrice);
        } else if (allTimeHighClose.equals(s.adjClose) && stopAt != null && sPrev != null
                && sPrev.order == OrderAction.IGNORE) {
            s.order = OrderAction.BUY;
            boughtPrice = s.adjClose;
            s.boughtPrice = boughtPrice;
        } else if (sPrev != null && (sPrev.order == OrderAction.HOLD || sPrev.order == OrderAction.BUY)) {
            s.order = OrderAction.HOLD;
        } else {
            s.order = OrderAction.IGNORE;
        }
        index++;
    }

    ServletOutputStream out = response.getOutputStream();
    out.println(lines[0]
            + ",Split,All Time High Close,True Range,ATR10,Stop At,Order State,Bought Price,Sold Price,Sold Difference");
    for (Stock s : dayPrices)
        out.println(s.getCSV());

}

From source file:org.fineract.module.stellar.horizonadapter.HorizonServerUtilities.java

/**
 * Creates a line of trust between stellar accounts for one currency, and up to a maximum amount.
 *
 * @param stellarAccountPrivateKey the key of the account doing the trusting
 * @param issuingStellarAccountId the account Id of the account to be trusted.
 * @param assetCode the currency symbol of the currency to be trusted.  See
 *                 https://www.stellar.org/developers/learn/concepts/assets.html
 *                 for a description of how to create a valid asset code.
 * @param maximumAmount the maximum amount of the currency to be trusted.
 *
 * @throws InvalidConfigurationException if the horizon server named in the configuration cannot
 * be reached.  Either the address is wrong or the horizon server named is't running, or there is
 * a problem with the network./*from   w w  w  .  j  a v a2 s .  c om*/
 * @throws StellarTrustlineAdjustmentFailedException if the creation of the trustline failed for any
 * other reason.
 */
public BigDecimal setTrustLineSize(final char[] stellarAccountPrivateKey,
        final StellarAccountId issuingStellarAccountId, final String assetCode, final BigDecimal maximumAmount)
        throws InvalidConfigurationException, StellarTrustlineAdjustmentFailedException {
    logger.info("HorizonServerUtilities.setTrustLineSize");
    final KeyPair trustingAccountKeyPair = KeyPair.fromSecretSeed(stellarAccountPrivateKey);
    final Account trustingAccount = accounts.getUnchecked(trustingAccountKeyPair.getAccountId());

    final Asset asset = StellarAccountHelpers.getAsset(assetCode, issuingStellarAccountId);

    final BigDecimal balance = getAccount(trustingAccountKeyPair).getBalanceOfAsset(asset);

    //Can't make it smaller than the balance
    final BigDecimal trustSize = balance.max(maximumAmount);

    final Transaction.Builder trustTransactionBuilder = new Transaction.Builder(trustingAccount);

    final ChangeTrustOperation trustOperation = new ChangeTrustOperation.Builder(asset,
            StellarAccountHelpers.bigDecimalToStellarBalance(trustSize)).build();

    trustTransactionBuilder.addOperation(trustOperation);

    submitTransaction(trustingAccount, trustTransactionBuilder, trustingAccountKeyPair,
            StellarTrustlineAdjustmentFailedException::trustLineTransactionFailed);

    return trustSize;
}

From source file:com.benfante.minimark.blo.ResultCalculationBo.java

private void evaluateClosedQuestion(ClosedQuestionFilling closedQuestionFilling, String evaluationType,
        BigDecimal minimumEvaluation) {
    BigDecimal result = new BigDecimal("0.00");
    if (evaluationType == null
            || Assessment.EVALUATION_CLOSED_SUM_CORRECT_MINUS_WRONG_ANSWERS.equals(evaluationType)) {
        final BigDecimal weightCorrect = closedQuestionFilling.weightCorrectAnswers();
        final BigDecimal weightSelectedCorrect = closedQuestionFilling.weightSelectedCorrectAnswers();
        final BigDecimal weightWrong = closedQuestionFilling.weightWrongAnswers();
        final BigDecimal weightSelectedWrong = closedQuestionFilling.weightSelectedWrongAnswers();
        BigDecimal normalizedCorrect = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightCorrect)) {
            // nc = #selectedCorrect/#correct
            normalizedCorrect = weightSelectedCorrect.divide(weightCorrect, 2, RoundingMode.HALF_EVEN);
        }//from   ww  w. j a v a 2  s.  c om
        BigDecimal normalizedWrong = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightWrong)) {
            // nw = #selectedWrong/#wrong
            normalizedWrong = weightSelectedWrong.divide(weightWrong, 2, RoundingMode.HALF_EVEN);
        }
        // r = nc-nw
        result = normalizedCorrect.subtract(normalizedWrong);
    } else if (Assessment.EVALUATION_CLOSED_SUM_CORRECT_ANSWERS.equals(evaluationType)) {
        final BigDecimal weightCorrect = closedQuestionFilling.weightCorrectAnswers();
        final BigDecimal weightSelectedCorrect = closedQuestionFilling.weightSelectedCorrectAnswers();
        result = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightCorrect)) {
            // r = #selectedCorrect/#correct
            result = weightSelectedCorrect.divide(weightCorrect, 2, RoundingMode.HALF_EVEN);
        }
    }
    // r = max(r, minimumEvaluation)
    if (minimumEvaluation != null) {
        result = result.max(minimumEvaluation);
    }
    closedQuestionFilling.setMark(result);
}

From source file:net.sourceforge.fenixedu.domain.student.Registration.java

final public BigDecimal calculateAverage() {
    final ICurriculum curriculum = getCurriculum();
    final BigDecimal weighted = curriculum.getAverage();

    switch (getAverageType()) {
    case SIMPLE:/* w w  w  .ja v  a  2  s  .c om*/
        curriculum.setAverageType(AverageType.SIMPLE);
        return curriculum.getAverage();
    case BEST:
        curriculum.setAverageType(AverageType.SIMPLE);
        final BigDecimal simple = curriculum.getAverage();

        return weighted.max(simple);
    default:
        return weighted;
    }
}

From source file:org.cirdles.calamari.algorithms.TukeyBiweight.java

public static ValueModel calculateTukeyBiweightMean(String name, double tuningConstant, double[] values) {
    // guarantee termination
    BigDecimal epsilon = BigDecimal.ONE.movePointLeft(10);
    int iterationMax = 100;
    int iterationCounter = 0;

    int n = values.length;
    // initial mean is median
    BigDecimal mean = new BigDecimal(calculateMedian(values));

    // initial sigma is median absolute deviation from mean = median (MAD)
    double deviations[] = new double[n];
    for (int i = 0; i < values.length; i++) {
        deviations[i] = StrictMath.abs(values[i] - mean.doubleValue());
    }/*from  ww  w  .j  a  va2 s.co m*/
    BigDecimal sigma = new BigDecimal(calculateMedian(deviations)).max(BigDecimal.valueOf(SQUID_TINY_VALUE));

    BigDecimal previousMean;
    BigDecimal previousSigma;

    do {
        iterationCounter++;
        previousMean = mean;
        previousSigma = sigma;

        // init to zeroes
        BigDecimal[] deltas = new BigDecimal[n];
        BigDecimal[] u = new BigDecimal[n];
        BigDecimal sa = BigDecimal.ZERO;
        BigDecimal sb = BigDecimal.ZERO;
        BigDecimal sc = BigDecimal.ZERO;

        BigDecimal tee = new BigDecimal(tuningConstant).multiply(sigma);

        for (int i = 0; i < n; i++) {
            deltas[i] = new BigDecimal(values[i]).subtract(mean);
            if (tee.compareTo(deltas[i].abs()) > 0) {
                deltas[i] = new BigDecimal(values[i]).subtract(mean);
                u[i] = deltas[i].divide(tee, MathContext.DECIMAL128);
                BigDecimal uSquared = u[i].multiply(u[i]);
                sa = sa.add(deltas[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)).pow(2));
                sb = sb.add(BigDecimal.ONE.subtract(uSquared)
                        .multiply(BigDecimal.ONE.subtract(new BigDecimal(5.0).multiply(uSquared))));
                sc = sc.add(u[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)));
            }
        }

        sigma = bigDecimalSqrtBabylonian(sa.multiply(new BigDecimal(n))).divide(sb.abs(),
                MathContext.DECIMAL128);
        sigma = sigma.max(BigDecimal.valueOf(SQUID_TINY_VALUE));
        mean = previousMean.add(tee.multiply(sc).divide(sb, MathContext.DECIMAL128));

    } // both tests against epsilon must pass OR iterations top out
      // april 2016 Simon B discovered we need 101 iterations possible, hence the "<=" below
    while (((sigma.subtract(previousSigma).abs().divide(sigma, MathContext.DECIMAL128).compareTo(epsilon) > 0)//
            || mean.subtract(previousMean).abs().divide(mean, MathContext.DECIMAL128).compareTo(epsilon) > 0)//
            && (iterationCounter <= iterationMax));

    return new ValueModel(name, mean, "ABS", sigma);
}

From source file:org.kalypso.grid.GeoGridUtilities.java

/**
 * gets the min and max values for the given {@link ICoverageCollection}
 *///from w  ww.  java 2 s  .co  m
public static BigDecimal[] getMinMax(final ICoverageCollection covCollection) throws Exception {
    final BigDecimal[] minmax = new BigDecimal[2];

    BigDecimal minValue = new BigDecimal(Double.MAX_VALUE).setScale(4, BigDecimal.ROUND_HALF_UP);
    BigDecimal maxValue = new BigDecimal(-Double.MAX_VALUE).setScale(4, BigDecimal.ROUND_HALF_UP);

    final IFeatureBindingCollection<ICoverage> coverages = covCollection.getCoverages();
    for (final ICoverage coverage : coverages) {
        final IGeoGrid grid = GeoGridUtilities.toGrid(coverage);

        final BigDecimal min = grid.getMin();
        final BigDecimal max = grid.getMax();

        minValue = minValue.min(min);
        maxValue = maxValue.max(max);
    }

    minmax[0] = minValue;
    minmax[1] = maxValue;

    return minmax;
}

From source file:org.kalypso.grid.GeoGridUtilities.java

public static Range<BigDecimal> calculateRange(final ICoverage[] coverages) {
    // get min / max
    BigDecimal min = new BigDecimal(Double.MAX_VALUE);
    BigDecimal max = new BigDecimal(-Double.MAX_VALUE);

    for (final ICoverage coverage : coverages) {
        try {//from w w w . java  2 s . c o m
            final IGeoGrid geoGrid = GeoGridUtilities.toGrid(coverage);
            min = min.min(geoGrid.getMin());
            max = max.max(geoGrid.getMax());

            // dispose it
            geoGrid.dispose();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    final BigDecimal rangeMin = min;
    final BigDecimal rangeMax = max;

    return Range.between(rangeMin, rangeMax);
}