[英]Java: Dealing with Exponentiation
我有這個程序的問題,我必須計算base ^ expo的值,base是實數,而exponent是整數。 隨着(95.123)^12
我期待548815620517731830194541.899025343415715973535967221869852721
,但我的程序產生548815620517732160000000.000000
,這是錯誤的。 請建議一個更好的方法。
// declare variables and read values
double myBase = scan.nextDouble();
int myExponent = scan.nextInt();
// display result
System.out.printf("%f", Math.pow(myBase, myExponent));
嘗試使用BigDecimal
例:
BigDecimal base = new BigDecimal("some number");
int exponent = ..;
BigDecimal result = base.pow(exponent);
Java中的double
類型是IEEE
雙精度,只有53位精度。 因此,您將獲得最接近真實答案的double
值。
由於結果的大幅度,最接近的double
值相差大於1
。 您可以通過調用Math.ulp
方法 (最后一個單位)來驗證這一點。
System.out.println(Math.ulp(Math.pow(myBase, myExponent)));
這輸出:
6.7108864E7
即使精確度,連續的double
值也相差6700萬。
作為替代方案,您可以使用BigDecimal
,例如
BigDecimal myBase= new BigDecimal(scan.next());
int myExponent= scan.nextInt();
//displays result
System.out.println(myBase.pow(myExponent));
輸出:
548815620517731830194541.899025343415715973535967221869852721
請注意, 此處的pow
采用int
,而不是另一個BigDecimal
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.