簡體   English   中英

為負指數產生錯誤結果的 power to n 實現

[英]Power to n implementation that produces wrong results for negative exponent

pow(x, n)方法的以下(天真)實現中,完全忽略任何優化方法,我發現以下問題:

public double pow(double x, int n) {  
  boolean negative = n < 0;  
  long power = Math.abs(n);  
  double ans = 1.0;  
  for(long i = 0; i < power; i++) {  
    ans = ans * x;  
  }    
  return negative ? 1.0/ans: ans;  
}  

在這里我假設對於負指數的情況我簡單地計算x^n然后返回1/(x^n)因為例如2^(-3) = 1/(2^3)

問題:
代碼在以下情況下失敗:
pow(2.00000, -2147483648)
output 是1.00000而預期的正確結果是0.00000

如果我按如下方式更改代碼:

public double pow(double x, int n) {  
  long power = n;  
  if(power < 0) {  
    x = 1 / x;  
    power = -power;
  }  
  double ans = 1.0;  
  for(long i = 0; i < power; i++) {  
    ans = ans * x;  
  }    
  return ans;  
}  

結果是正確的!

那么這些方法之間有什么區別呢? 我期待他們是等價的,但他們不是

Math.abs(n)仍然是一個int ,后來它被賦值給一個long ,因此, -2147483648 -2147483648這在Math.abs(int)的文檔中有說明)。 對於負邊界,循環不執行迭代。

Math.abs((long)n)可以解決這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM