2016-08-15 45 views
1

所以我用數值方法計算e(圖片中的第三行)。使用數值方法進行e計算時的浮點不準確

enter image description here

我正在增加元件的編號i使用的每個迭代。當我執行程序時,浮點變量的行爲方式我不明白。這是程序和結果。

import java.util.Scanner; 

    public class Test { 

     public static void main(String[] args) { 

      Scanner input = new Scanner(System.in); 

      int factorial = 1; 
      int counter = 0; 
      int iterationNumber; 
      double total = 0; 
      int tempCounter; 

      System.out.print("Enter iteration number: "); 
      iterationNumber = input.nextInt(); 

      while (counter <= iterationNumber) { 

      tempCounter = counter; 

      while ((tempCounter - 1) > 0) { 
       factorial *= tempCounter; 
       tempCounter--; 
      } 

      total += ((double)1/factorial); 
      System.out.println(total); 

      factorial = 1; 
      counter ++; 
      } 
     } 
    } 

enter image description here

所以我的問題是,爲什麼e值開始,而不是增加後減少?我想了解浮點變量在這個程序中的行爲以及它背後的邏輯。

另一個問題是爲什麼它開始說無窮大?

+0

因爲當1 /(n!)變得太小,你有一個流動點溢出,所以值變負,總和你的結果變得更小。 – Blobonat

+0

嘗試使用'BigDecimal'進行這些計算。您仍然必須定義精確度和舍入模式,但仍然可以獲得更好的精度和更高的數值範圍。 – Thomas

回答

3

n!快速超過Integer.MAX_VALUE並溢出到負數。然後,您會爲您的總數加上一個負數 - 從而減少。

您可以使用BigDecimal進行計算。它比較慢,但會完成這項工作。