Java Code Examples for java.math.MathContext#getPrecision()

The following examples show how to use java.math.MathContext#getPrecision() . 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: BigDecimalMath.java    From big-math with MIT License 6 votes vote down vote up
/**
 * Calculates the arc sine (inverted sine) of {@link BigDecimal} x.
 * 
 * <p>See: <a href="http://en.wikipedia.org/wiki/Arcsine">Wikipedia: Arcsine</a></p>
 * 
 * @param x the {@link BigDecimal} to calculate the arc sine for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated arc sine {@link BigDecimal} with the precision specified in the <code>mathContext</code>
 * @throws ArithmeticException if x &gt; 1 or x &lt; -1
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 */
public static BigDecimal asin(BigDecimal x, MathContext mathContext) {
	checkMathContext(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 asin(x.negate(), mathContext).negate();
	}
	
	MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode());

	if (x.compareTo(BigDecimal.valueOf(0.707107)) >= 0) {
		BigDecimal xTransformed = sqrt(ONE.subtract(x.multiply(x)), mc);
		return acos(xTransformed, mathContext);
	}

	BigDecimal result = AsinCalculator.INSTANCE.calculate(x, mc);
	return round(result, mathContext);
}
 
Example 2
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 6 votes vote down vote up
public static BigDecimal asin(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 asin(x.negate(), mathContext).negate();
	}
	
	MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode());

	if (x.compareTo(BigDecimal.valueOf(0.707107)) >= 0) {
		BigDecimal xTransformed = BigDecimalMath.sqrt(ONE.subtract(x.multiply(x, mc), mc), mc);
		return acos(xTransformed, mathContext);
	}

	BigDecimal result = AsinCalculator.INSTANCE.calculate(x, mc);
	return result.round(mathContext);
}
 
Example 3
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 6 votes vote down vote up
public static BigDecimal logAreaHyperbolicTangent(BigDecimal x, MathContext mathContext) {
	// http://en.wikipedia.org/wiki/Logarithm#Calculation
	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
	BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1);
	
	BigDecimal magic = x.subtract(ONE, mc).divide(x.add(ONE), mc);
	
	BigDecimal result = ZERO;
	BigDecimal step;
	int i = 0;
	do {
		int doubleIndexPlusOne = i * 2 + 1; 
		step = BigDecimalMath.pow(magic, doubleIndexPlusOne, mc).divide(valueOf(doubleIndexPlusOne), mc);

		result = result.add(step, mc);
		
		i++;
	} while (step.abs().compareTo(acceptableError) > 0);
	
	result = result.multiply(TWO, mc);
	
	return result.round(mathContext);
}
 
Example 4
Source File: StatisticalUtilities.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
public static BigDecimal sqrt(BigDecimal x, MathContext mc) {
        BigDecimal g = x.divide(TWO, mc);
        boolean done = false;
        final int maxIterations = mc.getPrecision() + 1;		
        for (int i = 0; !done && i < maxIterations; i++) {
                // r = (x/g + g) / 2
                BigDecimal r = x.divide(g, mc);
                r = r.add(g);
                r = r.divide(TWO, mc);
                done = r.equals(g);
                g = r;
        }
        return g;
}
 
Example 5
Source File: BigDecimalMath.java    From big-math with MIT License 5 votes vote down vote up
/**
 * Calculates the factorial of the specified {@link BigDecimal}.
 *
 * <p>This implementation uses
 * <a href="https://en.wikipedia.org/wiki/Spouge%27s_approximation">Spouge's approximation</a>
 * to calculate the factorial for non-integer values.</p>
 *
 * <p>This involves calculating a series of constants that depend on the desired precision.
 * Since this constant calculation is quite expensive (especially for higher precisions),
 * the constants for a specific precision will be cached
 * and subsequent calls to this method with the same precision will be much faster.</p>
 *
 * <p>It is therefore recommended to do one call to this method with the standard precision of your application during the startup phase
 * and to avoid calling it with many different precisions.</p>
 *
 * <p>See: <a href="https://en.wikipedia.org/wiki/Factorial#Extension_of_factorial_to_non-integer_values_of_argument">Wikipedia: Factorial - Extension of factorial to non-integer values of argument</a></p>
 *
 * @param x the {@link BigDecimal}
 * @param mathContext the {@link MathContext} used for the result
 * @return the factorial {@link BigDecimal}
 * @throws ArithmeticException if x is a negative integer value (-1, -2, -3, ...)
 * @throws UnsupportedOperationException if x is a non-integer value and the {@link MathContext} has unlimited precision
 * @see #factorial(int)
 * @see #gamma(BigDecimal, MathContext)
 */
public static BigDecimal factorial(BigDecimal x, MathContext mathContext) {
	if (isIntValue(x)) {
		return round(factorial(x.intValueExact()), mathContext);
	}

	// https://en.wikipedia.org/wiki/Spouge%27s_approximation
	checkMathContext(mathContext);
	MathContext mc = new MathContext(mathContext.getPrecision() << 1, mathContext.getRoundingMode());

	int a = mathContext.getPrecision() * 13 / 10;
	List<BigDecimal> constants = getSpougeFactorialConstants(a);

	BigDecimal bigA = BigDecimal.valueOf(a);

	boolean negative = false;
	BigDecimal factor = constants.get(0);
	for (int k = 1; k < a; k++) {
		BigDecimal bigK = BigDecimal.valueOf(k);
		factor = factor.add(constants.get(k).divide(x.add(bigK), mc));
		negative = !negative;
	}

	BigDecimal result = pow(x.add(bigA), x.add(BigDecimal.valueOf(0.5)), mc);
	result = result.multiply(exp(x.negate().subtract(bigA), mc));
	result = result.multiply(factor);

	return round(result, mathContext);
}
 
Example 6
Source File: BigDecimalMath.java    From big-math with MIT License 5 votes vote down vote up
/**
 * Calculates the tangens of {@link BigDecimal} x.
 * 
 * <p>See: <a href="http://en.wikipedia.org/wiki/Tangens">Wikipedia: Tangens</a></p>
 * 
 * @param x the {@link BigDecimal} to calculate the tangens for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated tangens {@link BigDecimal} with the precision specified in the <code>mathContext</code>
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 */
public static BigDecimal tan(BigDecimal x, MathContext mathContext) {
	checkMathContext(mathContext);
	if (x.signum() == 0) {
		return ZERO;
	}

	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
	BigDecimal result = sin(x, mc).divide(cos(x, mc), mc);
	return round(result, mathContext);
}
 
Example 7
Source File: BigDecimalMath.java    From big-math with MIT License 5 votes vote down vote up
/**
 * Calculates the arc cosine (inverted cosine) of {@link BigDecimal} x.
 * 
 * <p>See: <a href="http://en.wikipedia.org/wiki/Arccosine">Wikipedia: Arccosine</a></p>
 * 
 * @param x the {@link BigDecimal} to calculate the arc cosine for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated arc sine {@link BigDecimal} with the precision specified in the <code>mathContext</code>
 * @throws ArithmeticException if x &gt; 1 or x &lt; -1
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 */
public static BigDecimal acos(BigDecimal x, MathContext mathContext) {
	checkMathContext(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 = pi(mc).divide(TWO, mc).subtract(asin(x, mc));
	return round(result, mathContext);
}
 
Example 8
Source File: PrecisionScaleRoundedOperator.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the rounded Operator from scale and roundingMode
 * @param mathContext the math context, not null.
 * @return the {@link MonetaryOperator} using the scale and {@link RoundingMode} used in parameter
 * @throws NullPointerException when the {@link MathContext} is null
 * @throws IllegalArgumentException if {@link MathContext#getPrecision()} is lesser than zero
 * @throws IllegalArgumentException if {@link MathContext#getRoundingMode()} is {@link RoundingMode#UNNECESSARY}
 * @see RoundingMode
 */
public static PrecisionScaleRoundedOperator of(int scale, MathContext mathContext) {

	requireNonNull(mathContext);

	if(RoundingMode.UNNECESSARY.equals(mathContext.getRoundingMode())) {
	   throw new IllegalArgumentException("To create the ScaleRoundedOperator you cannot use the RoundingMode.UNNECESSARY on MathContext");
	}

	if(mathContext.getPrecision() <= 0) {
		throw new IllegalArgumentException("To create the ScaleRoundedOperator you cannot use the zero precision on MathContext");
	}
	return new PrecisionScaleRoundedOperator(scale, mathContext);
}
 
Example 9
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 5 votes vote down vote up
public static BigDecimal rootAdaptivePrecision(BigDecimal n, BigDecimal x, MathContext mathContext, int initialPrecision) {
	switch (x.signum()) {
	case 0:
		return ZERO;
	case -1:
		throw new ArithmeticException("Illegal root(x) for x < 0: x = " + x);
	}

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

	BigDecimal nMinus1 = n.subtract(ONE);
	BigDecimal result = x.divide(TWO, MathContext.DECIMAL32);
	int adaptivePrecision = initialPrecision;
	BigDecimal step;

	do {
		adaptivePrecision = adaptivePrecision * 3;
		if (adaptivePrecision > maxPrecision) {
			adaptivePrecision = maxPrecision;
		}
		MathContext mc = new MathContext(adaptivePrecision, mathContext.getRoundingMode());

		step = x.divide(BigDecimalMath.pow(result, nMinus1, mc), mc).subtract(result, mc).divide(n, mc);
		result = result.add(step, mc);
	} while (adaptivePrecision < maxPrecision || step.abs().compareTo(acceptableError) > 0);
	
	return result.round(mathContext);
}
 
Example 10
Source File: BigComplexMath.java    From big-math with MIT License 5 votes vote down vote up
/**
 * Calculates the natural logarithm of {@link BigComplex} x in the complex domain.
 *
 * <p>See: <a href="https://en.wikipedia.org/wiki/Complex_logarithm">Wikipedia: Complex logarithm</a></p>
 *
 * @param x the {@link BigComplex} to calculate the natural logarithm for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated natural logarithm {@link BigComplex} with the precision specified in the <code>mathContext</code>
 */
public static BigComplex log(BigComplex x, MathContext mathContext) {
	// https://en.wikipedia.org/wiki/Complex_logarithm
	MathContext mc1 = new MathContext(mathContext.getPrecision() + 20, mathContext.getRoundingMode());
	MathContext mc2 = new MathContext(mathContext.getPrecision() + 5, mathContext.getRoundingMode());

	return BigComplex.valueOf(
			BigDecimalMath.log(x.abs(mc1), mc1).round(mathContext),
			x.angle(mc2)).round(mathContext);
}
 
Example 11
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 5 votes vote down vote up
public static BigDecimal logUsingSqrt(BigDecimal x, MathContext mathContext, BiFunction<BigDecimal, MathContext, BigDecimal> logFunction) {
	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());

	BigDecimal sqrtX = BigDecimalMath.sqrt(x, mc);
	BigDecimal result = logFunction.apply(sqrtX, mc).multiply(TWO, mc);

	return result.round(mathContext);
}
 
Example 12
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 4 votes vote down vote up
/**
 * Broadhurst ladder sequence.
 *
 * @param a  The vector of 8 integer arguments
 * @param mc Specification of the accuracy of the result
 * @return S_(n, p)(a)
 * @see \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}
 */
static protected BigDecimal broadhurstBBP(final int n, final int p, final int a[], MathContext mc) {
    /* Explore the actual magnitude of the result first with a quick estimate.
    */
    double x = 0.0;


    for (int k = 1; k < 10; k++) {
        x += a[(k - 1) % 8] / Math.pow(2., p * (k + 1) / 2) / Math.pow((double) k, n);
    }
    /* Convert the relative precision and estimate of the result into an absolute precision.
     */


    double eps = prec2err(x, mc.getPrecision());
    /* Divide this through the number of terms in the sum to account for error accumulation
     * The divisor 2^(p(k+1)/2) means that on the average each 8th term in k has shrunk by
     * relative to the 8th predecessor by 1/2^(4p). 1/2^(4pc) = 10^(-precision) with c the 8term
     * cycles yields c=log_2( 10^precision)/4p = 3.3*precision/4p with k=8c
     */


    int kmax = (int) (6.6 * mc.getPrecision() / p);
    /* Now eps is the absolute error in each term */
    eps /= kmax;
    BigDecimal res = BigDecimal.ZERO;


    for (int c = 0;; c++) {
        Rational r = new Rational();


        for (int k = 0; k < 8; k++) {
            Rational tmp = new Rational(BigInteger.valueOf(a[k]), BigInteger.valueOf((1 + 8 * c + k)).pow(n));
            /* floor( (pk+p)/2)
             */


            int pk1h = p * (2 + 8 * c + k) / 2;
            tmp = tmp.divide(BigInteger.ONE.shiftLeft(pk1h));
            r = r.add(tmp);


        }
        if (Math.abs(r.doubleValue()) < eps) {
            break;
        }
        MathContext mcloc = new MathContext(1 + err2prec(r.doubleValue(), eps));
        res = res.add(r.BigDecimalValue(mcloc));


    }
    return res.round(mc);


}
 
Example 13
Source File: BigDecimalMath.java    From big-math with MIT License 4 votes vote down vote up
private static BigDecimal expIntegralFractional(BigDecimal x, MathContext mathContext) {
	BigDecimal integralPart = integralPart(x);
	
	if (integralPart.signum() == 0) {
		return expTaylor(x, mathContext);
	}
	
	BigDecimal fractionalPart = x.subtract(integralPart);

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

       BigDecimal z = ONE.add(fractionalPart.divide(integralPart, mc));
       BigDecimal t = expTaylor(z, mc);

       BigDecimal result = pow(t, integralPart.intValueExact(), mc);

	return round(result, mathContext);
}
 
Example 14
Source File: BigComplexMath.java    From big-math with MIT License 3 votes vote down vote up
/**
 * Calculates the natural exponent of {@link BigComplex} x (e<sup>x</sup>) in the complex domain.
 *
 * <p>See: <a href="https://en.wikipedia.org/wiki/Exponential_function#Complex_plane">Wikipedia: Exponent (Complex plane)</a></p>
 *
 * @param x the {@link BigComplex} to calculate the exponent for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated exponent {@link BigComplex} with the precision specified in the <code>mathContext</code>
 */
public static BigComplex exp(BigComplex x, MathContext mathContext) {
	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());

	BigDecimal expRe = BigDecimalMath.exp(x.re, mc);
	return BigComplex.valueOf(
			expRe.multiply(BigDecimalMath.cos(x.im, mc), mc).round(mathContext),
			expRe.multiply(BigDecimalMath.sin(x.im, mc), mc)).round(mathContext);
}
 
Example 15
Source File: BigDecimalMath.java    From big-math with MIT License 3 votes vote down vote up
/**
 * Calculates the arc hyperbolic sine (inverse hyperbolic sine) of {@link BigDecimal} x.
 * 
 * <p>See: <a href="https://en.wikipedia.org/wiki/Hyperbolic_function">Wikipedia: Hyperbolic function</a></p>
 * 
 * @param x the {@link BigDecimal} to calculate the arc hyperbolic sine for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated arc hyperbolic sine {@link BigDecimal} with the precision specified in the <code>mathContext</code>
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 */
public static BigDecimal asinh(BigDecimal x, MathContext mathContext) {
	checkMathContext(mathContext);
	MathContext mc = new MathContext(mathContext.getPrecision() + 10, mathContext.getRoundingMode());
	BigDecimal result = log(x.add(sqrt(x.multiply(x, mc).add(ONE, mc), mc)), mc);
	return round(result, mathContext);
}
 
Example 16
Source File: BigDecimalMath.java    From big-math with MIT License 3 votes vote down vote up
/**
 * Calculates the arc hyperbolic cotangens (inverse hyperbolic cotangens) of {@link BigDecimal} x.
 * 
 * <p>See: <a href="https://en.wikipedia.org/wiki/Hyperbolic_function">Wikipedia: Hyperbolic function</a></p>
 * 
 * @param x the {@link BigDecimal} to calculate the arc hyperbolic cotangens for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated arc hyperbolic cotangens {@link BigDecimal} with the precision specified in the <code>mathContext</code>
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 */
public static BigDecimal acoth(BigDecimal x, MathContext mathContext) {
	checkMathContext(mathContext);
	MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode());
	BigDecimal result = log(x.add(ONE).divide(x.subtract(ONE), mc), mc).multiply(ONE_HALF);
	return round(result, mathContext);
}
 
Example 17
Source File: BigDecimalMath.java    From big-math with MIT License 3 votes vote down vote up
/**
 * Calculates the hyperbolic cotangens of {@link BigDecimal} x.
 * 
 * <p>See: <a href="https://en.wikipedia.org/wiki/Hyperbolic_function">Wikipedia: Hyperbolic function</a></p>
 * 
 * @param x the {@link BigDecimal} to calculate the hyperbolic cotangens for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated hyperbolic cotangens {@link BigDecimal} with the precision specified in the <code>mathContext</code>
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 */
public static BigDecimal coth(BigDecimal x, MathContext mathContext) {
	checkMathContext(mathContext);
	MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode());
	BigDecimal result = cosh(x, mc).divide(sinh(x, mc), mc);
	return round(result, mathContext);
}
 
Example 18
Source File: BigComplexMath.java    From big-math with MIT License 3 votes vote down vote up
/**
 * Calculates the sine (sinus) of {@link BigComplex} x in the complex domain.
 *
 * <p>See: <a href="https://en.wikipedia.org/wiki/Sine#Sine_with_a_complex_argument">Wikipedia: Sine (Sine with a complex argument)</a></p>
 *
 * @param x the {@link BigComplex} to calculate the sine for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated sine {@link BigComplex} with the precision specified in the <code>mathContext</code>
 */
public static BigComplex sin(BigComplex x, MathContext mathContext) {
	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
	
	return BigComplex.valueOf(
			BigDecimalMath.sin(x.re, mc).multiply(BigDecimalMath.cosh(x.im, mc), mc).round(mathContext),
			BigDecimalMath.cos(x.re, mc).multiply(BigDecimalMath.sinh(x.im, mc), mc).round(mathContext));
}
 
Example 19
Source File: BigComplexMath.java    From big-math with MIT License 2 votes vote down vote up
/**
 * Calculates the arc cotangens (inverted cotangens) of {@link BigComplex} x in the complex domain.
 *
 * <p>See: <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Extension_to_complex_plane">Wikipedia: Inverse trigonometric functions (Extension to complex plane)</a></p>
 *
 * @param x the {@link BigComplex} to calculate the arc cotangens for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated arc cotangens {@link BigComplex} with the precision specified in the <code>mathContext</code>
 */
public static BigComplex acot(BigComplex x, MathContext mathContext) {
	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());

	return log(x.add(I, mc).divide(x.subtract(I, mc), mc), mc).divide(I, mc).divide(TWO, mc).round(mathContext);
}
 
Example 20
Source File: BigComplexMath.java    From big-math with MIT License 2 votes vote down vote up
/**
 * Calculates the arc cosine (inverted cosine) of {@link BigComplex} x in the complex domain.
 *
 * <p>See: <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Extension_to_complex_plane">Wikipedia: Inverse trigonometric functions (Extension to complex plane)</a></p>
 *
 * @param x the {@link BigComplex} to calculate the arc cosine for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated arc cosine {@link BigComplex} with the precision specified in the <code>mathContext</code>
 */
public static BigComplex acos(BigComplex x, MathContext mathContext) {
	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());

	return I.negate().multiply(log(x.add(sqrt(x.multiply(x, mc).subtract(BigComplex.ONE, mc), mc), mc), mc), mc).round(mathContext);
}