Search in sources :

Example 26 with MathContext

use of java.math.MathContext in project openhab1-addons by openhab.

the class PlexSession method updateProgress.

private void updateProgress() {
    if (duration > 0) {
        BigDecimal progress = new BigDecimal("100").divide(new BigDecimal(duration), new MathContext(100, RoundingMode.HALF_UP)).multiply(new BigDecimal(viewOffset)).setScale(2, RoundingMode.HALF_UP);
        progress = BigDecimal.ZERO.max(progress);
        progress = new BigDecimal("100").min(progress);
        this.progress = progress;
        this.endTime = new Date(System.currentTimeMillis() + (duration - viewOffset));
    }
}
Also used : BigDecimal(java.math.BigDecimal) MathContext(java.math.MathContext) Date(java.util.Date)

Example 27 with MathContext

use of java.math.MathContext in project XobotOS by xamarin.

the class Formatter method transformG.

private void transformG(StringBuilder result) {
    int precision = formatToken.getPrecision();
    if (precision == 0) {
        precision = 1;
    }
    formatToken.setPrecision(precision);
    double d = ((Number) arg).doubleValue();
    if (d == 0.0) {
        precision--;
        formatToken.setPrecision(precision);
        transformF(result);
        return;
    }
    boolean requireScientificRepresentation = true;
    d = Math.abs(d);
    if (Double.isInfinite(d)) {
        precision = formatToken.getPrecision();
        precision--;
        formatToken.setPrecision(precision);
        transformE(result);
        return;
    }
    BigDecimal b = new BigDecimal(d, new MathContext(precision));
    d = b.doubleValue();
    long l = b.longValue();
    if (d >= 1 && d < Math.pow(10, precision)) {
        if (l < Math.pow(10, precision)) {
            requireScientificRepresentation = false;
            precision -= String.valueOf(l).length();
            precision = precision < 0 ? 0 : precision;
            l = Math.round(d * Math.pow(10, precision + 1));
            if (String.valueOf(l).length() <= formatToken.getPrecision()) {
                precision++;
            }
            formatToken.setPrecision(precision);
        }
    } else {
        l = b.movePointRight(4).longValue();
        if (d >= Math.pow(10, -4) && d < 1) {
            requireScientificRepresentation = false;
            precision += 4 - String.valueOf(l).length();
            l = b.movePointRight(precision + 1).longValue();
            if (String.valueOf(l).length() <= formatToken.getPrecision()) {
                precision++;
            }
            l = b.movePointRight(precision).longValue();
            if (l >= Math.pow(10, precision - 4)) {
                formatToken.setPrecision(precision);
            }
        }
    }
    if (requireScientificRepresentation) {
        precision = formatToken.getPrecision();
        precision--;
        formatToken.setPrecision(precision);
        transformE(result);
    } else {
        transformF(result);
    }
}
Also used : BigDecimal(java.math.BigDecimal) MathContext(java.math.MathContext)

Example 28 with MathContext

use of java.math.MathContext in project voltdb by VoltDB.

the class VoltDecimalHelper method roundToScale.

/**
     * Round a BigDecimal number to a scale, given the rounding mode.
     * Note that the precision of the result can depend not only on its original
     * precision and scale and the desired scale, but also on its value.
     * For example, when rounding up with scale 2:<br>
     *     9.1999 with input scale 4 and precision 5 returns 9.20 with precision 3 (down 2).<br>
     *     9.9999 with input scale 4 and precision 5 returns 10.00 with precision 4 (down 1).<br>
     *     91.9999 with input scale 4 and precision 6 returns 92.00 with precision 4 (down 2).
     * @param bd the input value of arbitrary scale and precision
     * @param scale the desired scale of the return value
     * @param mode the rounding algorithm to use
     * @return the rounded value approximately equal to bd, but having the desired scale
     */
private static final BigDecimal roundToScale(BigDecimal bd, int scale, RoundingMode mode) throws RuntimeException {
    int lostScaleDigits = bd.scale() - scale;
    if (lostScaleDigits <= 0) {
        return bd;
    }
    if (!isRoundingEnabled()) {
        throw new RuntimeException(String.format("Decimal scale %d is greater than the maximum %d", bd.scale(), kDefaultScale));
    }
    int desiredPrecision = Math.max(1, bd.precision() - lostScaleDigits);
    MathContext mc = new MathContext(desiredPrecision, mode);
    BigDecimal nbd = bd.round(mc);
    if (nbd.scale() != scale) {
        nbd = nbd.setScale(scale);
    }
    assert (nbd.scale() == scale);
    return nbd;
}
Also used : MathContext(java.math.MathContext) BigDecimal(java.math.BigDecimal)

Example 29 with MathContext

use of java.math.MathContext in project Protocol-Adapter-IEC61850 by OSGP.

the class DistributionAutomationGetPQValuesRequestMessageProcessor method processPQValue.

private DataSampleDto processPQValue(final ModelNode node) {
    Date ts = null;
    String type = null;
    BigDecimal value = null;
    if (node.getChildren() != null) {
        ts = this.findBdaTimestampNodeValue(node);
        final ModelNode floatNode = this.findBdaFloat32NodeInConstructedDataAttribute(node);
        if (floatNode != null) {
            type = node.getName() + "." + floatNode.getParent().getName() + "." + floatNode.getName();
            value = new BigDecimal(((BdaFloat32) floatNode).getFloat(), new MathContext(3, RoundingMode.HALF_EVEN));
        }
    }
    return new DataSampleDto(type, ts, value);
}
Also used : DataSampleDto(org.osgpfoundation.osgp.dto.da.iec61850.DataSampleDto) BdaFloat32(org.openmuc.openiec61850.BdaFloat32) FcModelNode(org.openmuc.openiec61850.FcModelNode) ModelNode(org.openmuc.openiec61850.ModelNode) Date(java.util.Date) BigDecimal(java.math.BigDecimal) MathContext(java.math.MathContext)

Example 30 with MathContext

use of java.math.MathContext in project GDSC-SMLM by aherbert.

the class PoissonCalculatorTest method canComputeLogLikelihoodRatio.

private void canComputeLogLikelihoodRatio(BaseNonLinearFunction nlf) {
    System.out.println(nlf.name);
    int n = maxx * maxx;
    double[] a = new double[] { 1 };
    // Simulate Poisson process
    nlf.initialise(a);
    RandomDataGenerator rdg = new RandomDataGenerator(new Well19937c(30051977));
    double[] x = new double[n];
    double[] u = new double[n];
    for (int i = 0; i < n; i++) {
        u[i] = nlf.eval(i);
        if (u[i] > 0)
            x[i] = rdg.nextPoisson(u[i]);
    }
    double ll = PoissonCalculator.logLikelihood(u, x);
    double mll = PoissonCalculator.maximumLogLikelihood(x);
    double llr = -2 * (ll - mll);
    double llr2 = PoissonCalculator.logLikelihoodRatio(u, x);
    System.out.printf("llr=%f, llr2=%f\n", llr, llr2);
    Assert.assertEquals("Log-likelihood ratio", llr, llr2, llr * 1e-10);
    double[] op = new double[x.length];
    for (int i = 0; i < n; i++) op[i] = PoissonCalculator.maximumLikelihood(x[i]);
    double max = Double.NEGATIVE_INFINITY;
    double maxa = 0;
    //TestSettings.setLogLevel(gdsc.smlm.TestSettings.LogLevel.DEBUG);
    int df = n - 1;
    ChiSquaredDistributionTable table = ChiSquaredDistributionTable.createUpperTailed(0.05, df);
    ChiSquaredDistributionTable table2 = ChiSquaredDistributionTable.createUpperTailed(0.001, df);
    System.out.printf("Chi2 = %f (q=%.3f), %f (q=%.3f)  %f %b  %f\n", table.getCrititalValue(df), table.getSignificanceValue(), table2.getCrititalValue(df), table2.getSignificanceValue(), ChiSquaredDistributionTable.computeQValue(24, 2), ChiSquaredDistributionTable.createUpperTailed(0.05, 2).reject(24, 2), ChiSquaredDistributionTable.getChiSquared(1e-6, 2));
    for (int i = 5; i <= 15; i++) {
        a[0] = (double) i / 10;
        nlf.initialise(a);
        for (int j = 0; j < n; j++) u[j] = nlf.eval(j);
        ll = PoissonCalculator.logLikelihood(u, x);
        llr = PoissonCalculator.logLikelihoodRatio(u, x);
        BigDecimal product = new BigDecimal(1);
        double ll2 = 0;
        for (int j = 0; j < n; j++) {
            double p1 = PoissonCalculator.likelihood(u[j], x[j]);
            ll2 += Math.log(p1);
            double ratio = p1 / op[j];
            product = product.multiply(new BigDecimal(ratio));
        }
        llr2 = -2 * Math.log(product.doubleValue());
        double p = ChiSquaredDistributionTable.computePValue(llr, df);
        double q = ChiSquaredDistributionTable.computeQValue(llr, df);
        TestSettings.info("a=%f, ll=%f, ll2=%f, llr=%f, llr2=%f, product=%s, p=%f, q=%f (reject=%b @ %.3f, reject=%b @ %.3f)\n", a[0], ll, ll2, llr, llr2, product.round(new MathContext(4)).toString(), p, q, table.reject(llr, df), table.getSignificanceValue(), table2.reject(llr, df), table2.getSignificanceValue());
        if (max < ll) {
            max = ll;
            maxa = a[0];
        }
        // too small to store in a double.
        if (product.doubleValue() > 0) {
            Assert.assertEquals("Log-likelihood", ll, ll2, Math.abs(ll2) * 1e-10);
            Assert.assertEquals("Log-likelihood ratio", llr, llr2, Math.abs(llr) * 1e-10);
        }
    }
    Assert.assertEquals("max", 1, maxa, 0);
}
Also used : RandomDataGenerator(org.apache.commons.math3.random.RandomDataGenerator) Well19937c(org.apache.commons.math3.random.Well19937c) BigDecimal(java.math.BigDecimal) MathContext(java.math.MathContext)

Aggregations

MathContext (java.math.MathContext)237 BigDecimal (java.math.BigDecimal)224 RoundingMode (java.math.RoundingMode)73 BigInteger (java.math.BigInteger)71 List (java.util.List)9 Test (org.junit.Test)8 BigDecimalMath (ch.obermuhlner.math.big.BigDecimalMath)7 Arrays (java.util.Arrays)7 Function (java.util.function.Function)7 StopWatch (ch.obermuhlner.math.big.example.StopWatch)3 IOException (java.io.IOException)3 Random (java.util.Random)3 Context (ch.obermuhlner.math.big.BigFloat.Context)2 FileWriter (java.io.FileWriter)2 PrintWriter (java.io.PrintWriter)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 RandomDataGenerator (org.apache.commons.math3.random.RandomDataGenerator)2 Well19937c (org.apache.commons.math3.random.Well19937c)2 DataCell (org.knime.core.data.DataCell)2