(a+b)^n (n は BigDecimal 変数の実数値) を計算しようとしていますが、BigDecimal.pow は整数値のみを受け入れるように設計されています。
質問する
1376 次
2 に答える
1
入力が double でサポートされる大きさの範囲内にあり、結果の有効桁数が 15 桁を超える必要がない場合は、(a+b) と n を double に変換し、Math.pow を使用して、結果を BigDecimal に変換します。
于 2012-11-19T18:22:05.753 に答える
1
指数に整数を使用している限り、単純なループを使用して x^y を計算できます。
public static BigDecimal pow(BigDecimal x, BigInteger y) {
if(y.compareTo(BigInteger.ZERO)==0) return BigDecimal.valueOf(1); //If the exponent is 0 then return 1 because x^0=1
BigDecimal out = x;
BigInteger i = BigInteger.valueOf(1);
while(i.compareTo(y.abs())<0) { //for(BigDecimal i = 1; i<y.abs(); i++) but in BigDecimal form
out = out.multiply(x);
i = i.add(BigInteger.ONE);
}
if(y.compareTo(BigInteger.ZERO)>0) {
return out;
} else if(y.compareTo(BigInteger.ZERO))<0) {
return BigDecimal.ONE.divide(out, MathContext.DECIMAL128); //Just so that it doesn't throw an error of non-terminating decimal expansion (ie. 1.333333333...)
} else return null; //In case something goes wrong
}
または BigDecimal x および y の場合:
public static BigDecimal powD(BigDecimal x, BigDecimal y) {
return pow(x, y.toBigInteger());
}
お役に立てれば!
于 2013-11-30T18:02:07.923 に答える