2012-11-19 33 views
2

試圖計算(a + b)^ n其中n是BigDecimal變量中的實數值,但BigDecimal.pow僅用於接受整數值。如何計算沒有整數大數點表示的功率?

+2

[BigDecimal的對數]的可能重複(http://stackoverflow.com/questions/739532/logarithm-of-a-bigdecimal) –

+0

如果指數不符合Integer,結果將是_very_大。 –

+0

@JanDvorak'2.1234'怎麼樣? – assylias

回答

1

如果輸入值在double支持的幅度範圍內,並且結果中不需要超過15個有效數字,則將(a + b)和n轉換爲double,使用Math.pow並將結果回到BigDecimal。

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()); 
} 

希望這有助於!