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

The following examples show how to use java.math.BigDecimal#pow() . 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: BigDecimalCalculations.java    From oopsla15-artifact with Eclipse Public License 1.0 6 votes vote down vote up
public static BigDecimal pow(BigDecimal a, BigDecimal b, int scale) {
	if (a.signum() == -1) {
		throw new ArithmeticException("x < 0");
	}
	if (a.equals(BigDecimal.ZERO)) {
		return BigDecimal.ZERO;
	}
	scale = Math.max(Math.max(a.precision(), b.precision()), scale) + 1;
	MathContext mc = new MathContext(scale, RoundingMode.HALF_UP);
	BigDecimal remainer = b.remainder(BigDecimal.ONE, mc);
	if (remainer.equals(BigDecimal.ZERO)) {
		return a.pow(b.intValue(), mc);
	}
	// else we have to do the more expansive route:
	// a^b=exp(b*ln(a)) 
	return exp(b.multiply(ln(a, scale), mc), scale).setScale(scale - 1, RoundingMode.HALF_EVEN);
}
 
Example 2
Source File: DefaultNumericType.java    From jdmn with Apache License 2.0 6 votes vote down vote up
public BigDecimal numericExponentiation(BigDecimal first, int second) {
    if (first == null) {
        return null;
    }

    try {
        if (second < 0) {
            return first.pow(second, MATH_CONTEXT);
        } else if (second == 0) {
            return BigDecimal.ONE;
        } else {
            BigDecimal temp = first.pow(-second, MATH_CONTEXT);
            return BigDecimal.ONE.divide(temp, MATH_CONTEXT);
        }
    } catch (Exception e) {
        String message = String.format("numericExponentiation(%s, %s)", first, second);
        logError(message, e);
        return null;
    }
}
 
Example 3
Source File: SPRTMethod.java    From SIMVA-SoS with Apache License 2.0 6 votes vote down vote up
public void updateResult(int res){
    if( !(res == 1 || res == 0) )
        return;
    this.numSamples++;
    if(res == 1)
        this.dm++;
    if(numSamples > 1){
        BigDecimal p1m_before = new BigDecimal(String.valueOf(1));
        p1m_before = p1m_before.subtract(this.p1);
        p1m_before = p1m_before.pow(this.numSamples-this.dm, MathContext.DECIMAL32);
        this.p1m = this.p1.pow(this.dm, MathContext.DECIMAL32);
        this.p1m = this.p1m.multiply(p1m_before, MathContext.DECIMAL32);

        BigDecimal p0m_before = new BigDecimal(String.valueOf(1));
        p0m_before = p0m_before.subtract(this.p0);
        p0m_before = p0m_before.pow(this.numSamples - this.dm, MathContext.DECIMAL32);

        this.p0m = this.p0.pow(this.dm, MathContext.DECIMAL32);
        this.p0m = this.p0m.multiply(p0m_before, MathContext.DECIMAL32);
    }
}
 
Example 4
Source File: UserUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public static String generateUniqueString(int length) {
  int totalChars = alphabet.length;
  BigDecimal exponent = BigDecimal.valueOf(totalChars);
  exponent = exponent.pow(length);
  String code = "";
  BigDecimal number = new BigDecimal(rand.nextInt(1000000));
  BigDecimal num = number.multiply(largePrimeNumber).remainder(exponent);
  code = baseN(num, totalChars);
  int codeLenght = code.length();
  if (codeLenght < length) {
    for (int i = codeLenght; i < length; i++) {
      code = code + alphabet[rand.nextInt(totalChars - 1)];
    }
  }
  if (NumberUtils.isNumber(code.substring(1, 2)) || NumberUtils.isNumber(code.substring(2, 3))) {
    return code;
  } else {
    code = code.substring(0, 1) + alphabet[rand.nextInt(9)] + code.substring(2);
    return code;
  }
}
 
Example 5
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * Raise to an integer power and round.
 *
 * @param x The base.
 * @param n The exponent.
 * @return x^n.
 */
static public BigDecimal powRound(final BigDecimal x, final int n) {
    /* The relative error in the result is n times the relative error in the input.
     * The estimation is slightly optimistic due to the integer rounding of the logarithm.
     */
    MathContext mc = new MathContext(x.precision() - (int) Math.log10((double) (Math.abs(n))));
    return x.pow(n, mc);
}
 
Example 6
Source File: MathLib.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@TLFunctionAnnotation("Returns the value of the first argument raised to the power of the second argument.")
public static final BigDecimal pow(TLFunctionCallContext context, BigDecimal argument, BigDecimal power) {
	int exponent = power.intValue();
	
	if (exponent < 0) { // CLO-12062: pass MathContext to allow negative exponents
		return argument.pow(exponent, TransformLangExecutor.MAX_PRECISION);
	} else {
    	// MathContext might change precision, use the original implementation for non-negative exponents for backward compatibility
    	return argument.pow(exponent); 
	}
}
 
Example 7
Source File: Operators.java    From beanshell with Apache License 2.0 5 votes vote down vote up
static Object bigDecimalBinaryOperation(BigDecimal lhs, BigDecimal rhs, int kind)
    throws UtilEvalError
{
    switch(kind)
    {
        // arithmetic
        case PLUS:
            return lhs.add(rhs);

        case MINUS:
            return lhs.subtract(rhs);

        case STAR:
            return lhs.multiply(rhs);

        case SLASH:
            return lhs.divide(rhs);

        case MOD:
        case MODX:
            return lhs.remainder(rhs);

        case POWER:
        case POWERX:
            return lhs.pow(rhs.intValue());

        // can't shift floats
        case LSHIFT:
        case LSHIFTX:
        case RSIGNEDSHIFT:
        case RSIGNEDSHIFTX:
        case RUNSIGNEDSHIFT:
        case RUNSIGNEDSHIFTX:
            throw new UtilEvalError("Can't shift floatingpoint values");

    }
    throw new InterpreterError(
            "Unimplemented binary float operator");
}
 
Example 8
Source File: BigDecimalArithmeticTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * pow(int)
 */
public void testPow() {
    String a = "123121247898748298842980";
    int aScale = 10;
    int exp = 10;
    String c = "8004424019039195734129783677098845174704975003788210729597" +
               "4875206425711159855030832837132149513512555214958035390490" +
               "798520842025826.594316163502809818340013610490541783276343" +
               "6514490899700151256484355936102754469438371850240000000000";
    int cScale = 100;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal result = aNumber.pow(exp);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", cScale, result.scale());
}
 
Example 9
Source File: OperatorPower.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	SpelNodeImpl leftOp = getLeftOperand();
	SpelNodeImpl rightOp = getRightOperand();

	Object leftOperand = leftOp.getValueInternal(state).getValue();
	Object rightOperand = rightOp.getValueInternal(state).getValue();

	if (leftOperand instanceof Number && rightOperand instanceof Number) {
		Number leftNumber = (Number) leftOperand;
		Number rightNumber = (Number) rightOperand;

		if (leftNumber instanceof BigDecimal) {
			BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
			return new TypedValue(leftBigDecimal.pow(rightNumber.intValue()));
		}
		else if (leftNumber instanceof BigInteger) {
			BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
			return new TypedValue(leftBigInteger.pow(rightNumber.intValue()));
		}
		else if (leftNumber instanceof Double || rightNumber instanceof Double) {
			return new TypedValue(Math.pow(leftNumber.doubleValue(), rightNumber.doubleValue()));
		}
		else if (leftNumber instanceof Float || rightNumber instanceof Float) {
			return new TypedValue(Math.pow(leftNumber.floatValue(), rightNumber.floatValue()));
		}

		double d = Math.pow(leftNumber.doubleValue(), rightNumber.doubleValue());
		if (d > Integer.MAX_VALUE || leftNumber instanceof Long || rightNumber instanceof Long) {
			return new TypedValue((long) d);
		}
		else {
			return new TypedValue((int) d);
		}
	}

	return state.operate(Operation.POWER, leftOperand, rightOperand);
}
 
Example 10
Source File: OperatorPower.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	SpelNodeImpl leftOp = getLeftOperand();
	SpelNodeImpl rightOp = getRightOperand();

	Object leftOperand = leftOp.getValueInternal(state).getValue();
	Object rightOperand = rightOp.getValueInternal(state).getValue();

	if (leftOperand instanceof Number && rightOperand instanceof Number) {
		Number leftNumber = (Number) leftOperand;
		Number rightNumber = (Number) rightOperand;

		if (leftNumber instanceof BigDecimal) {
			BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
			return new TypedValue(leftBigDecimal.pow(rightNumber.intValue()));
		}
		else if (leftNumber instanceof BigInteger) {
			BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
			return new TypedValue(leftBigInteger.pow(rightNumber.intValue()));
		}
		else if (leftNumber instanceof Double || rightNumber instanceof Double) {
			return new TypedValue(Math.pow(leftNumber.doubleValue(), rightNumber.doubleValue()));
		}
		else if (leftNumber instanceof Float || rightNumber instanceof Float) {
			return new TypedValue(Math.pow(leftNumber.floatValue(), rightNumber.floatValue()));
		}

		double d = Math.pow(leftNumber.doubleValue(), rightNumber.doubleValue());
		if (d > Integer.MAX_VALUE || leftNumber instanceof Long || rightNumber instanceof Long) {
			return new TypedValue((long) d);
		}
		else {
			return new TypedValue((int) d);
		}
	}

	return state.operate(Operation.POWER, leftOperand, rightOperand);
}
 
Example 11
Source File: Pow.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
	 * Built-in Java implementation of the pow function for integer exponents between -999999999...999999999.
	 * Only the <code>decPrec</code> leading digits of the output are correct!
	 * @param x
	 * @param n
	 * @return x^n
	 */
	static BigDecimal pow/*Java*/(BigDecimal x, int n, Precision decPrec) {
		// avoid rounding errors
		int innerDecPrec = decPrec.digits() + 4;
//		// avoid ArithmeticException (see comment in class PowTest):
//		if (innerDecPrec==1 && n>9) innerDecPrec = 2;
		// compute result at inner precision
		BigDecimal result = x.pow(n, new MathContext(innerDecPrec, RoundingMode.HALF_EVEN));
		// round to originally wanted output precision
		return decPrec.applyTo(result);
	}
 
Example 12
Source File: OperatorPower.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	SpelNodeImpl leftOp = getLeftOperand();
	SpelNodeImpl rightOp = getRightOperand();

	Object leftOperand = leftOp.getValueInternal(state).getValue();
	Object rightOperand = rightOp.getValueInternal(state).getValue();

	if (leftOperand instanceof Number && rightOperand instanceof Number) {
		Number leftNumber = (Number) leftOperand;
		Number rightNumber = (Number) rightOperand;

		if (leftNumber instanceof BigDecimal) {
			BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
			return new TypedValue(leftBigDecimal.pow(rightNumber.intValue()));
		}
		else if (leftNumber instanceof BigInteger) {
			BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
			return new TypedValue(leftBigInteger.pow(rightNumber.intValue()));
		}
		else if (leftNumber instanceof Double || rightNumber instanceof Double) {
			return new TypedValue(Math.pow(leftNumber.doubleValue(), rightNumber.doubleValue()));
		}
		else if (leftNumber instanceof Float || rightNumber instanceof Float) {
			return new TypedValue(Math.pow(leftNumber.floatValue(), rightNumber.floatValue()));
		}

		double d = Math.pow(leftNumber.doubleValue(), rightNumber.doubleValue());
		if (d > Integer.MAX_VALUE || leftNumber instanceof Long || rightNumber instanceof Long) {
			return new TypedValue((long) d);
		}
		else {
			return new TypedValue((int) d);
		}
	}

	return state.operate(Operation.POWER, leftOperand, rightOperand);
}
 
Example 13
Source File: BigDecimalUtil.java    From objectlabkit with Apache License 2.0 5 votes vote down vote up
/**
 * Private utility method used to compute the square root of a BigDecimal.
 * 
 * @author Luciano Culacciatti 
 * @see <a href="http://www.codeproject.com/Tips/257031/Implementing-SqrtRoot-in-BigDecimal">http://www.codeproject.com/Tips/257031/Implementing-SqrtRoot-in-BigDecimal</a>
 */
private static BigDecimal sqrtNewtonRaphson(final BigDecimal c, final BigDecimal xn, final BigDecimal precision) {
    BigDecimal fx = xn.pow(2).add(c.negate());
    BigDecimal fpx = xn.multiply(new BigDecimal(2));
    BigDecimal xn1 = fx.divide(fpx, 2 * SQRT_DIG.intValue(), RoundingMode.HALF_DOWN);
    xn1 = xn.add(xn1.negate());
    BigDecimal currentSquare = xn1.pow(2);
    BigDecimal currentPrecision = currentSquare.subtract(c);
    currentPrecision = currentPrecision.abs();
    if (currentPrecision.compareTo(precision) <= -1) {
        return xn1;
    }
    return sqrtNewtonRaphson(c, xn1, precision);
}
 
Example 14
Source File: BigDecimalMath.java    From big-math with MIT License 4 votes vote down vote up
private static BigDecimal piChudnovski(MathContext mathContext) {
	MathContext mc = new MathContext(mathContext.getPrecision() + 10, mathContext.getRoundingMode());

	final BigDecimal value24 = BigDecimal.valueOf(24);
	final BigDecimal value640320 = BigDecimal.valueOf(640320);
	final BigDecimal value13591409 = BigDecimal.valueOf(13591409);
	final BigDecimal value545140134 = BigDecimal.valueOf(545140134);
	final BigDecimal valueDivisor = value640320.pow(3).divide(value24, mc);

	BigDecimal sumA = BigDecimal.ONE;
	BigDecimal sumB = BigDecimal.ZERO;

	BigDecimal a = BigDecimal.ONE;
	long dividendTerm1 = 5; // -(6*k - 5)
	long dividendTerm2 = -1; // 2*k - 1
	long dividendTerm3 = -1; // 6*k - 1
	BigDecimal kPower3 = BigDecimal.ZERO;
	
	long iterationCount = (mc.getPrecision()+13) / 14;
	for (long k = 1; k <= iterationCount; k++) {
		BigDecimal valueK = BigDecimal.valueOf(k);
		dividendTerm1 += -6;
		dividendTerm2 += 2;
		dividendTerm3 += 6;
		BigDecimal dividend = BigDecimal.valueOf(dividendTerm1).multiply(BigDecimal.valueOf(dividendTerm2)).multiply(BigDecimal.valueOf(dividendTerm3));
		kPower3 = valueK.pow(3);
		BigDecimal divisor = kPower3.multiply(valueDivisor, mc);
		a = a.multiply(dividend).divide(divisor, mc);
		BigDecimal b = valueK.multiply(a, mc);
		
		sumA = sumA.add(a);
		sumB = sumB.add(b);
	}
	
	final BigDecimal value426880 = BigDecimal.valueOf(426880);
	final BigDecimal value10005 = BigDecimal.valueOf(10005);
	final BigDecimal factor = value426880.multiply(sqrt(value10005, mc));
	BigDecimal pi = factor.divide(value13591409.multiply(sumA, mc).add(value545140134.multiply(sumB, mc)), mc);

	return round(pi, mathContext);
}
 
Example 15
Source File: ClickHouseRowBinaryInputStream.java    From clickhouse-jdbc with Apache License 2.0 4 votes vote down vote up
public BigDecimal readDecimal64(int scale) throws IOException {
    long i = in.readLong();
    BigDecimal ten = BigDecimal.valueOf(10);
    BigDecimal s = ten.pow(scale);
    return new BigDecimal(i).divide(s);
}
 
Example 16
Source File: ClickHouseRowBinaryStream.java    From clickhouse-jdbc with Apache License 2.0 4 votes vote down vote up
private BigInteger removeComma(BigDecimal num, int scale) {
    BigDecimal ten = BigDecimal.valueOf(10);
    BigDecimal s = ten.pow(scale);
    return num.multiply(s).toBigInteger();
}
 
Example 17
Source File: BigDecimalUtils.java    From simm-lib with MIT License 4 votes vote down vote up
public static BigDecimal square(BigDecimal b1) {
  return b1.pow(2);
}
 
Example 18
Source File: Quantity.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static BigDecimal getAmountInBytes(Quantity quantity) throws ArithmeticException {
  String value = "";
  if (quantity.getAmount() != null && quantity.getFormat() != null) {
    value = quantity.getAmount() + quantity.getFormat();
  } else if (quantity.getAmount() != null) {
    value = quantity.getAmount();
  }

  if (value == null || value.isEmpty()) {
    throw new IllegalArgumentException("Invalid quantity value passed to parse");
  }
  // Append Extra zeroes if starting with decimal
  if (!Character.isDigit(value.indexOf(0)) && value.startsWith(".")) {
      value = "0" + value;
  }

  Quantity amountFormatPair = parse(value);
  String formatStr = amountFormatPair.getFormat();
  // Handle Decimal exponent case
  if ((formatStr.matches(AT_LEAST_ONE_DIGIT_REGEX)) && formatStr.length() > 1) {
    int exponent = Integer.parseInt(formatStr.substring(1));
    return new BigDecimal("10").pow(exponent, MathContext.DECIMAL64).multiply(new BigDecimal(amountFormatPair.getAmount()));
  }

  BigDecimal digit = new BigDecimal(amountFormatPair.getAmount());
  BigDecimal multiple = new BigDecimal("1");
  BigDecimal binaryFactor = new BigDecimal("2");
  BigDecimal decimalFactor = new BigDecimal("10");

  switch (formatStr) {
    case "Ki":
      multiple = binaryFactor.pow(10, MathContext.DECIMAL64);
      break;
    case "Mi":
      multiple = binaryFactor.pow(20, MathContext.DECIMAL64);
      break;
    case "Gi":
      multiple = binaryFactor.pow(30, MathContext.DECIMAL64);
      break;
    case "Ti":
      multiple = binaryFactor.pow(40, MathContext.DECIMAL64);
      break;
    case "Pi":
      multiple = binaryFactor.pow(50, MathContext.DECIMAL64);
      break;
    case "Ei":
      multiple = binaryFactor.pow(60, MathContext.DECIMAL64);
      break;
    case "n":
      multiple = decimalFactor.pow(-9, MathContext.DECIMAL64);
      break;
    case "u":
      multiple = decimalFactor.pow(-6, MathContext.DECIMAL64);
      break;
    case "m":
      multiple = decimalFactor.pow(-3, MathContext.DECIMAL64);
      break;
    case "k":
      multiple = decimalFactor.pow(3, MathContext.DECIMAL64);
      break;
    case "M":
      multiple = decimalFactor.pow(6, MathContext.DECIMAL64);
      break;
    case "G":
      multiple = decimalFactor.pow(9, MathContext.DECIMAL64);
      break;
    case "T":
      multiple = decimalFactor.pow(12, MathContext.DECIMAL64);
      break;
    case "P":
      multiple = decimalFactor.pow(15, MathContext.DECIMAL64);
      break;
    case "E":
      multiple = decimalFactor.pow(18, MathContext.DECIMAL64);
      break;
  }

  return digit.multiply(multiple);
}
 
Example 19
Source File: BigDecimalExtensions.java    From xtext-lib with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * The <code>power</code> operator.
 * 
 * @param a
 *            a BigDecimal. May not be <code>null</code>.
 * @param exponent
 *            the exponent.
 * @return <code>a.pow(b)</code>
 * @throws NullPointerException
 *             if {@code a} is <code>null</code>.
 */
@Pure
@Inline(value="$1.pow($2)")
public static BigDecimal operator_power(BigDecimal a, int exponent) {
	return a.pow(exponent);
}
 
Example 20
Source File: Pow.java    From symja_android_library with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Built-in Java implementation of the pow function for integer exponents between 0...999999999.
 * The result is computed exactly.
 * @param x
 * @param n
 * @return x^n
 */
static BigDecimal nnPowJava(BigDecimal x, int n) {
	return x.pow(n);
}