Java Code Examples for java.math.BigDecimal#round()

The following examples show how to use java.math.BigDecimal#round() . 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 File: BigDecimalMathExperimental.java    From big-math with MIT License 6 votes vote down vote up
public static BigDecimal rootFixPrecision(BigDecimal n, BigDecimal x, MathContext mathContext) {
	switch (x.signum()) {
	case 0:
		return ZERO;
	case -1:
		throw new ArithmeticException("Illegal root(x) for x < 0: x = " + x);
	}

	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
	BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1);

	BigDecimal factor = ONE.divide(n, mc);
	BigDecimal nMinus1 = n.subtract(ONE);
	BigDecimal result = x.divide(TWO, mc);
	BigDecimal step;

	do {
		step = factor.multiply(x.divide(BigDecimalMath.pow(result, nMinus1, mc), mc).subtract(result, mc), mc);
				
		result = result.add(step, mc);
	} while (step.abs().compareTo(acceptableError) > 0);
	
	return result.round(mathContext);
}
 
Example 2
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * The natural logarithm.
 *
 * @param r  The main argument, a strictly positive value.
 * @param mc The requirements on the precision.
 * @return ln(r).
 */
static public BigDecimal log(final Rational r, final MathContext mc) {
    /* the value is undefined if x is negative.
     */
    if (r.compareTo(Rational.ZERO) <= 0) {
        throw new ArithmeticException("Cannot take log of negative " + r.toString());
    } else if (r.compareTo(Rational.ONE) == 0) {
        return BigDecimal.ZERO;
    } else {
        /* log(r+epsr) = log(r)+epsr/r. Convert the precision to an absolute error in the result.
         * eps contains the required absolute error of the result, epsr/r.
         */
        double eps = prec2err(Math.log(r.doubleValue()), mc.getPrecision());
        /* Convert this further into a requirement of the relative precision in r, given that
         * epsr/r is also the relative precision of r. Add one safety digit.
         */
        MathContext mcloc = new MathContext(1 + err2prec(eps));
        final BigDecimal resul = log(r.BigDecimalValue(mcloc));
        return resul.round(mc);
    }
}
 
Example 3
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 6 votes vote down vote up
public static BigDecimal logUsingNewtonFixPrecision(BigDecimal x, MathContext mathContext) {
	// https://en.wikipedia.org/wiki/Natural_logarithm in chapter 'High Precision'
	// y = y + 2 * (x-exp(y)) / (x+exp(y))

	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
	BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1);
	
	BigDecimal result = BigDecimal.valueOf(Math.log(x.doubleValue()));
	BigDecimal step;
	
	do {
		BigDecimal expY = BigDecimalMath.exp(result, mc);
		step = TWO.multiply(x.subtract(expY, mc), mc).divide(x.add(expY, mc), mc);
		result = result.add(step);
	} while (step.abs().compareTo(acceptableError) > 0);

	return result.round(mathContext);
}
 
Example 4
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * The integer root.
 *
 * @param n the positive argument.
 * @param x the non-negative argument.
 * @return The n-th root of the BigDecimal rounded to the precision implied by x, x^(1/n).
 */
static public BigDecimal root(final int n, final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        throw new ArithmeticException("negative argument " + x.toString() + " of root");
    }
    if (n <= 0) {
        throw new ArithmeticException("negative power " + n + " of root");
    }
    if (n == 1) {
        return x;
    }
    /* start the computation from a double precision estimate */
    BigDecimal s = new BigDecimal(Math.pow(x.doubleValue(), 1.0 / n));
    /* this creates nth with nominal precision of 1 digit
     */
    final BigDecimal nth = new BigDecimal(n);
    /* Specify an internal accuracy within the loop which is
     * slightly larger than what is demanded by ’eps’ below.
     */
    final BigDecimal xhighpr = scalePrec(x, 2);
    MathContext mc = new MathContext(2 + x.precision());
    /* Relative accuracy of the result is eps.
     */
    final double eps = x.ulp().doubleValue() / (2 * n * x.doubleValue());
    for (;;) {
        /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being
         * smaller than the precision requested. The relative correction is (1-x/s^n)/n,
         */
        BigDecimal c = xhighpr.divide(s.pow(n - 1), mc);
        c = s.subtract(c);
        MathContext locmc = new MathContext(c.precision());
        c = c.divide(nth, locmc);
        s = s.subtract(c);
        if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) {
            break;
        }
    }
    return s.round(new MathContext(err2prec(eps)));
}
 
Example 5
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 5 votes vote down vote up
public static BigDecimal sqrtUsingNewtonAdaptivePrecisionImproved(BigDecimal x, MathContext mathContext) {
	switch (x.signum()) {
	case 0:
		return ZERO;
	case -1:
		throw new ArithmeticException("Illegal sqrt(x) for x < 0: x = " + x);
	}

	int maxPrecision = mathContext.getPrecision() + 4;
	BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1);

	BigDecimal result = BigDecimal.valueOf(Math.sqrt(x.doubleValue()));
	
	if (result.multiply(result, mathContext).compareTo(x) == 0) {
		return result.round(mathContext); // early exit if x is a square number
	}

	int adaptivePrecision = 17;
	BigDecimal last;

	do {
		last = result;
		adaptivePrecision = adaptivePrecision * 2;
		if (adaptivePrecision > maxPrecision) {
			adaptivePrecision = maxPrecision;
		}
		MathContext mc = new MathContext(adaptivePrecision, mathContext.getRoundingMode());
		result = x.divide(result, mc).add(last).divide(TWO, mc);
	} while (adaptivePrecision < maxPrecision || result.subtract(last).abs().compareTo(acceptableError) > 0);
	
	return result.round(mathContext);
}
 
Example 6
Source File: BigDecimalArithmeticTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * round(BigDecimal, MathContext)
 */
public void testRoundMathContextHALF_UP() {
    String a = "3736186567876876578956958765675671119238118911893939591735";
    int aScale = 45;
    int precision = 15;
    RoundingMode rm = RoundingMode.HALF_UP;
    MathContext mc = new MathContext(precision, rm);
    String res = "3736186567876.88";
    int resScale = 2;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal result = aNumber.round(mc);
    assertEquals("incorrect quotient value", res, result.toString());
    assertEquals("incorrect quotient scale", resScale, result.scale());
}
 
Example 7
Source File: PrecisionContextRoundedOperator.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Override
public MonetaryAmount apply(MonetaryAmount amount) {
	RoundedMoney roundedMoney = RoundedMoney.from(Objects.requireNonNull(amount));
	BigDecimal numberValue = roundedMoney.getNumber().numberValue(BigDecimal.class);
	BigDecimal numberRounded = numberValue.round(mathContext);
	return RoundedMoney.of(numberRounded, roundedMoney.getCurrency(), this);
}
 
Example 8
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 5 votes vote down vote up
public static BigDecimal sqrtUsingNewtonAdaptivePrecisionPrint(BigDecimal x, MathContext mathContext) {
	switch (x.signum()) {
	case 0:
		return ZERO;
	case -1:
		throw new ArithmeticException("Illegal sqrt(x) for x < 0: x = " + x);
	}

	int maxPrecision = mathContext.getPrecision() + 4;
	BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1);

	BigDecimal result = BigDecimal.valueOf(Math.sqrt(x.doubleValue()));
	int adaptivePrecision = 17;
	BigDecimal last;

	do {
		last = result;
		adaptivePrecision = adaptivePrecision * 2;
		if (adaptivePrecision > maxPrecision) {
			adaptivePrecision = maxPrecision;
		}
		MathContext mc = new MathContext(adaptivePrecision, mathContext.getRoundingMode());
		result = x.divide(result, mc).add(last).divide(TWO, mc);
		System.out.printf("%5d, ", countSameCharacters(last.toPlainString(), result.toPlainString()));
	} while (adaptivePrecision < maxPrecision || result.subtract(last).abs().compareTo(acceptableError) > 0);
	
	return result.round(mathContext);
}
 
Example 9
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * The inverse hyperbolic cosine.
 *
 * @param x The argument.
 * @return The arccosh(x) .
 */
static public BigDecimal acosh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ONE) < 0) {
        throw new ArithmeticException("Out of range argument cosh " + x.toString());
    } else if (x.compareTo(BigDecimal.ONE) == 0) {
        return BigDecimal.ZERO;
    } else {
        BigDecimal xhighpr = scalePrec(x, 2);
        /* arccosh(x) = log(x+sqrt(x^2-1))
         */
        BigDecimal logx = log(sqrt(xhighpr.pow(2).subtract(BigDecimal.ONE)).add(xhighpr));
        /* The absolute error in arcsinh x is err(x)/sqrt(x^2-1)
         */


        double xDbl = x.doubleValue();


        double eps = 0.5 * x.ulp().doubleValue() / Math.sqrt(xDbl * xDbl - 1.);
        MathContext mc = new MathContext(err2prec(logx.doubleValue(), eps));


        return logx.round(mc);


    }
}
 
Example 10
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 5 votes vote down vote up
public static BigDecimal acosUsingNewton(BigDecimal x, MathContext mathContext) {
	if (x.compareTo(ONE) > 0) {
		throw new ArithmeticException("Illegal acos(x) for x > 1: x = " + x);
	}
	if (x.compareTo(MINUS_ONE) < 0) {
		throw new ArithmeticException("Illegal acos(x) for x < -1: x = " + x);
	}

	MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode());

	BigDecimal result = BigDecimalMath.pi(mc).divide(TWO, mc).subtract(asinUsingNewton(x, mc), mc);
	return result.round(mathContext);
}
 
Example 11
Source File: TestUtil.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public static void assertRoundEquals(BigDecimal bd1, BigDecimal bd2) {
    bd1 = bd1.round(PDataType.DEFAULT_MATH_CONTEXT);
    bd2 = bd2.round(PDataType.DEFAULT_MATH_CONTEXT);
    if (bd1.compareTo(bd2) != 0) {
        fail("expected:<" + bd1 + "> but was:<" + bd2 + ">");
    }
}
 
Example 12
Source File: BigDecimalArithmeticTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * round(BigDecimal, MathContext)
 */
public void testRoundMathContextHALF_DOWN() {
    String a = "3736186567876876578956958765675671119238118911893939591735";
    int aScale = -45;
    int precision = 75;
    RoundingMode rm = RoundingMode.HALF_DOWN;
    MathContext mc = new MathContext(precision, rm);
    String res = "3.736186567876876578956958765675671119238118911893939591735E+102";
    int resScale = -45;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal result = aNumber.round(mc);
    assertEquals("incorrect quotient value", res, result.toString());
    assertEquals("incorrect quotient scale", resScale, result.scale());
}
 
Example 13
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 4 votes vote down vote up
public static BigDecimal asinUsingNewton(BigDecimal x, MathContext mathContext) {
		if (x.compareTo(ONE) > 0) {
			throw new ArithmeticException("Illegal asin(x) for x > 1: x = " + x);
		}
		if (x.compareTo(MINUS_ONE) < 0) {
			throw new ArithmeticException("Illegal asin(x) for x < -1: x = " + x);
		}
		
		if (x.signum() == -1) {
			return asinUsingNewton(x.negate(), mathContext).negate();
		}

		int maxPrecision = mathContext.getPrecision() + 4;

		BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1);
		MathContext maxMathContext = new MathContext(maxPrecision, mathContext.getRoundingMode());
		
		if (x.compareTo(BigDecimal.valueOf(0.707107)) >= 0) {
			BigDecimal xTransformed = BigDecimalMath.sqrt(ONE.subtract(x.multiply(x, maxMathContext), maxMathContext), maxMathContext);
			return acosUsingNewton(xTransformed, mathContext);
		}

		BigDecimal denominator = BigDecimalMath.cos(x, maxMathContext);

		BigDecimal result = BigDecimal.valueOf(Math.asin(x.doubleValue()));
		int adaptivePrecision = 17;
		BigDecimal step;
		
		do {
			adaptivePrecision = adaptivePrecision * 3;
			if (adaptivePrecision > maxPrecision) {
				adaptivePrecision = maxPrecision;
			}
			MathContext mc = new MathContext(adaptivePrecision, mathContext.getRoundingMode());

			BigDecimal nominator = BigDecimalMath.sin(result, mc).subtract(x, mc); 
			step = nominator.divide(denominator, mc);
			result = result.subtract(step, mc);
//			System.out.println(BigDecimalMath.exponent(step) + " : " + result);
		} while (step.abs().compareTo(acceptableError) > 0);

		return result.round(mathContext);
	}
 
Example 14
Source File: ScatterTest6.java    From ECharts with MIT License 4 votes vote down vote up
public Double round(Double d) {
    BigDecimal bigDecimal = new BigDecimal(d.toString());
    bigDecimal = bigDecimal.round(new MathContext(2, RoundingMode.HALF_UP));
    return bigDecimal.doubleValue();
}
 
Example 15
Source File: ScatterTest3.java    From ECharts with MIT License 4 votes vote down vote up
public Double round(Double d) {
    BigDecimal bigDecimal = new BigDecimal(d.toString());
    bigDecimal = bigDecimal.round(new MathContext(3, RoundingMode.HALF_UP));
    return bigDecimal.doubleValue();
}
 
Example 16
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 3 votes vote down vote up
/**
 * Multiply and round.
 *
 * @param x The left factor.
 * @param y The right factor.
 * @return The product x*y.
 */
static public BigDecimal multiplyRound(final BigDecimal x, final BigDecimal y) {
    BigDecimal resul = x.multiply(y);


    /* The estimation of the relative error in the result is the sum of the relative
     * errors |err(y)/y|+|err(x)/x|
     */
    MathContext mc = new MathContext(Math.min(x.precision(), y.precision()));


    return resul.round(mc);


}
 
Example 17
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 3 votes vote down vote up
/**
 * Multiply and round.
 *
 * @param x The left factor.
 * @param n The right factor.
 * @return The product x*n.
 */
static public BigDecimal multiplyRound(final BigDecimal x, final int n) {
    BigDecimal resul = x.multiply(new BigDecimal(n));
    /* The estimation of the absolute error in the result is |n*err(x)|
     */
    MathContext mc = new MathContext(n != 0 ? x.precision() : 0);


    return resul.round(mc);


}
 
Example 18
Source File: BigDecimalMath.java    From big-math with MIT License 2 votes vote down vote up
/**
 * Rounds the specified {@link BigDecimal} to the precision of the specified {@link MathContext}.
 *
 * <p>This method calls {@link BigDecimal#round(MathContext)}.</p>
 *
 * @param value the {@link BigDecimal} to round
 * @param mathContext the {@link MathContext} used for the result
 * @return the rounded {@link BigDecimal} value
 * @see BigDecimal#round(MathContext)
 * @see BigDecimalMath#roundWithTrailingZeroes(BigDecimal, MathContext)
 */
public static BigDecimal round(BigDecimal value, MathContext mathContext) {
 return value.round(mathContext);
}
 
Example 19
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 2 votes vote down vote up
/**
 * Pochhammer’s function.
 *
 * @param x The main argument.
 * @param n The non-negative index.
 * @return (x)_n = x(x+1)(x+2)*...*(x+n-1).
 */
static public BigDecimal pochhammer(final BigDecimal x, final int n) {
    /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33
     */
    if (n < 0) {
        throw new ProviderException("Unimplemented pochhammer with negative index " + n);
    } else if (n == 0) {
        return BigDecimal.ONE;
    } else {
        /* internally two safety digits
         */
        BigDecimal xhighpr = scalePrec(x, 2);
        BigDecimal resul = xhighpr;


        double xUlpDbl = x.ulp().doubleValue();


        double xDbl = x.doubleValue();
        /* relative error of the result is the sum of the relative errors of the factors
         */


        double eps = 0.5 * xUlpDbl / Math.abs(xDbl);


        for (int i = 1; i < n; i++) {
            eps += 0.5 * xUlpDbl / Math.abs(xDbl + i);


            resul = resul.multiply(xhighpr.add(new BigDecimal(i)));
            final MathContext mcloc = new MathContext(4 + err2prec(eps));
            resul = resul.round(mcloc);


        }
        return resul.round(new MathContext(err2prec(eps)));


    }
}
 
Example 20
Source File: BigFloat.java    From big-math with MIT License 2 votes vote down vote up
/**
 * Creates a {@link BigFloat} value with this context.
 *
 * @param value the source {@link BigDecimal} value
 *
 * @return the {@link BigFloat} value with this context (rounded to the precision of this context)
 */
public BigFloat valueOf(BigDecimal value) {
	return new BigFloat(value.round(mathContext), this);
}