java.math.BigDecimal.pow()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(12.2k)|赞(0)|评价(0)|浏览(600)

本文整理了Java中java.math.BigDecimal.pow()方法的一些代码示例,展示了BigDecimal.pow()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。BigDecimal.pow()方法的具体详情如下:
包路径:java.math.BigDecimal
类名称:BigDecimal
方法名:pow

BigDecimal.pow介绍

[英]Returns a new BigDecimal whose value is thisn. The scale of the result is n * this.scale().

x.pow(0) returns 1, even if x == 0.

Implementation Note: The implementation is based on the ANSI standard X3.274-1996 algorithm.
[中]返回值为thisn的新BigDecimal。结果的比例是n*this。比例()。
x、 pow(0)返回1,即使x==0。
实施说明:该实施基于ANSI标准X3。274-1996算法。

代码示例

代码示例来源:origin: looly/hutool

/**
 * 提供精确的幂运算
 * 
 * @param number 底数
 * @param n 指数
 * @return 幂的积
 * @since 4.1.0
 */
public static BigDecimal pow(BigDecimal number, int n) {
  return number.pow(n);
}

代码示例来源:origin: looly/hutool

/**
 * 提供精确的幂运算
 * 
 * @param number 底数
 * @param n 指数
 * @return 幂的积
 * @since 4.1.0
 */
public static BigDecimal pow(BigDecimal number, int n) {
  return number.pow(n);
}

代码示例来源:origin: web3j/web3j

Unit(String name, int factor) {
  this.name = name;
  this.weiFactor = BigDecimal.TEN.pow(factor);
}

代码示例来源:origin: deeplearning4j/nd4j

/**
 * 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);
} /* BigDecimalMath.powRound */

代码示例来源:origin: kiegroup/optaplanner

@Override
public HardMediumSoftBigDecimalScore power(double exponent) {
  BigDecimal exponentBigDecimal = BigDecimal.valueOf(exponent);
  // The (unspecified) scale/precision of the exponent should have no impact on the returned scale/precision
  // TODO FIXME remove .intValue() so non-integer exponents produce correct results
  // None of the normal Java libraries support BigDecimal.pow(BigDecimal)
  return new HardMediumSoftBigDecimalScore(
      (int) Math.floor(Math.pow(initScore, exponent)),
      hardScore.pow(exponentBigDecimal.intValue()).setScale(hardScore.scale(), RoundingMode.FLOOR),
      mediumScore.pow(exponentBigDecimal.intValue()).setScale(mediumScore.scale(), RoundingMode.FLOOR),
      softScore.pow(exponentBigDecimal.intValue()).setScale(softScore.scale(), RoundingMode.FLOOR));
}

代码示例来源:origin: kiegroup/optaplanner

@Override
public HardSoftBigDecimalScore power(double exponent) {
  // Intentionally not taken "new BigDecimal(multiplicand, MathContext.UNLIMITED)"
  // because together with the floor rounding it gives unwanted behaviour
  BigDecimal exponentBigDecimal = BigDecimal.valueOf(exponent);
  // The (unspecified) scale/precision of the exponent should have no impact on the returned scale/precision
  // TODO FIXME remove .intValue() so non-integer exponents produce correct results
  // None of the normal Java libraries support BigDecimal.pow(BigDecimal)
  return new HardSoftBigDecimalScore(
      (int) Math.floor(Math.pow(initScore, exponent)),
      hardScore.pow(exponentBigDecimal.intValue()).setScale(hardScore.scale(), RoundingMode.FLOOR),
      softScore.pow(exponentBigDecimal.intValue()).setScale(softScore.scale(), RoundingMode.FLOOR));
}

代码示例来源:origin: kiegroup/optaplanner

@Override
public SimpleBigDecimalScore power(double exponent) {
  // Intentionally not taken "new BigDecimal(multiplicand, MathContext.UNLIMITED)"
  // because together with the floor rounding it gives unwanted behaviour
  BigDecimal exponentBigDecimal = BigDecimal.valueOf(exponent);
  // The (unspecified) scale/precision of the exponent should have no impact on the returned scale/precision
  // TODO FIXME remove .intValue() so non-integer exponents produce correct results
  // None of the normal Java libraries support BigDecimal.pow(BigDecimal)
  return new SimpleBigDecimalScore(
      (int) Math.floor(Math.pow(initScore, exponent)),
      score.pow(exponentBigDecimal.intValue()).setScale(score.scale(), RoundingMode.FLOOR));
}

代码示例来源:origin: apache/drill

/**
 * Calculates and returns square root for specified BigDecimal
 * with specified number of digits alter decimal point.
 *
 * @param in    BigDecimal which square root should be calculated
 * @param scale number of digits alter decimal point in the result value.
 * @return square root for specified BigDecimal
 */
public static BigDecimal sqrt(BigDecimal in, int scale) {
 // unscaled BigInteger value from specified BigDecimal with doubled number of digits after decimal point
 // was used to calculate sqrt using Guava's BigIntegerMath.
 BigInteger valueWithDoubleMaxPrecision =
   in.multiply(BigDecimal.TEN.pow(scale * 2)).setScale(0, RoundingMode.HALF_UP).unscaledValue();
 return new BigDecimal(
   BigIntegerMath.sqrt(valueWithDoubleMaxPrecision, RoundingMode.HALF_UP), scale);
}

代码示例来源:origin: kiegroup/optaplanner

@Override
public BendableBigDecimalScore power(double exponent) {
  BigDecimal[] newHardScores = new BigDecimal[hardScores.length];
  BigDecimal[] newSoftScores = new BigDecimal[softScores.length];
  BigDecimal actualExponent = BigDecimal.valueOf(exponent);
  // The (unspecified) scale/precision of the exponent should have no impact on the returned scale/precision
  // TODO FIXME remove .intValue() so non-integer exponents produce correct results
  // None of the normal Java libraries support BigDecimal.pow(BigDecimal)
  for (int i = 0; i < newHardScores.length; i++) {
    BigDecimal hardScore = hardScores[i];
    newHardScores[i] = hardScore.pow(actualExponent.intValue()).setScale(hardScore.scale(), RoundingMode.FLOOR);
  }
  for (int i = 0; i < newSoftScores.length; i++) {
    BigDecimal softScore = softScores[i];
    newSoftScores[i] = softScore.pow(actualExponent.intValue()).setScale(softScore.scale(), RoundingMode.FLOOR);
  }
  return new BendableBigDecimalScore(
      (int) Math.floor(Math.pow(initScore, exponent)),
      newHardScores, newSoftScores);
}

代码示例来源:origin: org.codehaus.groovy/groovy

/**
 * Power of a BigDecimal to an integer certain exponent. If the
 * exponent is positive, call the BigDecimal.pow(int) method to
 * maintain precision. Called by the '**' operator.
 *
 * @param self     a BigDecimal
 * @param exponent an Integer exponent
 * @return a Number to the power of a the exponent
 */
public static Number power(BigDecimal self, Integer exponent) {
  if (exponent >= 0) {
    return self.pow(exponent);
  } else {
    return power(self, (double) exponent);
  }
}

代码示例来源:origin: jphp-group/jphp

private static BigDecimal bcpowImpl(BigDecimal base, BigInteger exp, int scale) {
  if (exp.compareTo(BigInteger.ZERO) == 0)
    return BigDecimal.ONE;
  boolean isNeg;
  if (exp.compareTo(BigInteger.ZERO) < 0) {
    isNeg = true;
    exp = exp.negate();
  }
  else
    isNeg = false;
  BigDecimal result = BigDecimal.ZERO;
  while (exp.compareTo(BigInteger.ZERO) > 0) {
    BigInteger expSub = exp.min(INTEGER_MAX);
    exp = exp.subtract(expSub);
    result = result.add(base.pow(expSub.intValue()));
  }
  if (isNeg)
    result = BigDecimal.ONE.divide(result, scale + 2, RoundingMode.DOWN);
  result = result.setScale(scale, RoundingMode.DOWN);
  if (result.compareTo(BigDecimal.ZERO) == 0)
    return BigDecimal.ZERO;
  result = result.stripTrailingZeros();
  return result;
}

代码示例来源:origin: stackoverflow.com

private static final BigDecimal SQRT_PRE = new BigDecimal(10).pow(SQRT_DIG.intValue());
  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();

代码示例来源:origin: plantuml/plantuml

public BigDecimal eval(Number vv1, Number vv2) {
    BigDecimal v1 = (BigDecimal) vv1;
    BigDecimal v2 = (BigDecimal) vv2;
    assertNotNull(v1, v2);
    /*- 
     * Thanks to Gene Marin:
     * http://stackoverflow.com/questions/3579779/how-to-do-a-fractional-power-on-bigdecimal-in-java
     */
    int signOf2 = ((BigDecimal) v2).signum();
    double dn1 = v1.doubleValue();
    v2 = v2.multiply(new BigDecimal(signOf2)); // n2 is now positive
    BigDecimal remainderOf2 = v2.remainder(BigDecimal.ONE);
    BigDecimal n2IntPart = v2.subtract(remainderOf2);
    BigDecimal intPow = v1.pow(n2IntPart.intValueExact(), mc);
    BigDecimal doublePow = new BigDecimal(Math.pow(dn1, remainderOf2.doubleValue()));
    BigDecimal result = intPow.multiply(doublePow, mc);
    if (signOf2 == -1) {
      result = BigDecimal.ONE.divide(result, mc.getPrecision(), RoundingMode.HALF_UP);
    }
    return result;
  }
});

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

/**
 * Returns the remainder amount if the passed in totalAmount was divided by the
 * quantity taking into account the normal unit of the currency (e.g. .01 for US).
 *
 * @param totalAmount
 * @param quantity
 * @return
 */
public static int calculateRemainder(Money totalAmount, int quantity) {
  if (totalAmount == null || totalAmount.isZero() || quantity == 0) {
    return 0;
  }
  // Use this to convert to a whole number (e.g. 1.05 becomes 105 in US currency).
  BigDecimal multiplier = new BigDecimal(10).pow(totalAmount.getAmount().scale());
  BigDecimal amount = totalAmount.getAmount().multiply(multiplier);
  BigDecimal remainder = amount.remainder(new BigDecimal(quantity), ROUND_FLOOR_MATH_CONTEXT);
  return remainder.toBigInteger().intValue();
}

代码示例来源:origin: spring-projects/spring-framework

return new TypedValue(leftBigDecimal.pow(rightNumber.intValue()));

代码示例来源:origin: deeplearning4j/nd4j

/**
 * The hypotenuse.
 *
 * @param x the first argument.
 * @param y the second argument.
 * @return the square root of the sum of the squares of the two arguments, sqrt(x^2+y^2).
 */
static public BigDecimal hypot(final BigDecimal x, final BigDecimal y) {
  /* compute x^2+y^2
   */
  BigDecimal z = x.pow(2).add(y.pow(2));
  /* truncate to the precision set by x and y. Absolute error = 2*x*xerr+2*y*yerr,
   * where the two errors are 1/2 of the ulp’s. Two intermediate protectio digits.
   */
  BigDecimal zerr = x.abs().multiply(x.ulp()).add(y.abs().multiply(y.ulp()));
  MathContext mc = new MathContext(2 + err2prec(z, zerr));
  /* Pull square root */
  z = sqrt(z.round(mc));
  /* Final rounding. Absolute error in the square root is (y*yerr+x*xerr)/z, where zerr holds 2*(x*xerr+y*yerr).
   */
  mc = new MathContext(err2prec(z.doubleValue(), 0.5 * zerr.doubleValue() / z.doubleValue()));
  return z.round(mc);
} /* BigDecimalMath.hypot */

代码示例来源:origin: deeplearning4j/nd4j

/**
 * The hypotenuse.
 *
 * @param n the first argument.
 * @param x the second argument.
 * @return the square root of the sum of the squares of the two arguments, sqrt(n^2+x^2).
 */
static public BigDecimal hypot(final int n, final BigDecimal x) {
  /* compute n^2+x^2 in infinite precision
   */
  BigDecimal z = (new BigDecimal(n)).pow(2).add(x.pow(2));
  /* Truncate to the precision set by x. Absolute error = in z (square of the result) is |2*x*xerr|,
   * where the error is 1/2 of the ulp. Two intermediate protection digits.
   * zerr is a signed value, but used only in conjunction with err2prec(), so this feature does not harm.
   */
  double zerr = x.doubleValue() * x.ulp().doubleValue();
  MathContext mc = new MathContext(2 + err2prec(z.doubleValue(), zerr));
  /* Pull square root */
  z = sqrt(z.round(mc));
  /* Final rounding. Absolute error in the square root is x*xerr/z, where zerr holds 2*x*xerr.
   */
  mc = new MathContext(err2prec(z.doubleValue(), 0.5 * zerr / z.doubleValue()));
  return z.round(mc);
} /* BigDecimalMath.hypot */

代码示例来源:origin: apache/hive

@HiveDecimalVersionV1
public HiveDecimalV1 pow(int n) {
 BigDecimal result = normalize(bd.pow(n), false);
 return result == null ? null : new HiveDecimalV1(result);
}

代码示例来源:origin: deeplearning4j/nd4j

/**
 * 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);
  }
} /* BigDecimalMath.acosh */

代码示例来源:origin: apache/ignite

/**
   * @param depositCache Deposit cache.
   * @param depositKey Deposit key.
   */
  private void checkDeposit(IgniteCache<String, BinaryObject> depositCache, String depositKey) {
    IgniteCache histCache = node.cache(DEPOSIT_HISTORY_CACHE).withKeepBinary();
    BinaryObject deposit = depositCache.get(depositKey);
    BigDecimal startBalance = deposit.field(BALANCE_ON_DAY_OPEN);
    BigDecimal balance = deposit.field(BALANCE);
    BigDecimal rate = deposit.field(MARGIN_RATE);
    BigDecimal expBalance;
    SqlFieldsQuery findDepositHist = new SqlFieldsQuery(DEPOSIT_OPERATION_COUNT_SQL);
    try (QueryCursor cursor1 = histCache.query(findDepositHist.setArgs(depositKey))) {
      Long cnt = (Long)((ArrayList)cursor1.iterator().next()).get(0);
      expBalance = startBalance.multiply(rate.add(BigDecimal.ONE).pow(cnt.intValue()));
    }
    expBalance = expBalance.setScale(2, BigDecimal.ROUND_DOWN);
    balance = balance.setScale(2, BigDecimal.ROUND_DOWN);
    if (checkBalance && !expBalance.equals(balance)) {
      node.log().error("Deposit " + depositKey + " has incorrect balance "
        + balance + " when expected " + expBalance, null);
      throw new IgniteException("Deposit " + depositKey + " has incorrect balance "
        + balance + " when expected " + expBalance);
    }
  }
}

相关文章