2014-09-12 78 views
0

我寫了下面的代碼...矩陣除了用怪異的結果

public class MatrixAddition 
{ 
    public static void main(String[] args) 
    { 

     double matrix[][] = { { 1.2, 3.3, 1.2 }, { 1.0, 2.2, 4.5 }, { 1.3, 4.5, 2.2 } }; 
     double matrix1[][] = { { 2.2, -3.3, 1.1 }, { 7.0, -2.2, 4.2 }, { 2.2, 0.0, 0.3 } }; 
     double result[][] = new double[matrix.length][matrix1.length]; 

     for(int iResult = 0; iResult < result.length; iResult++) { 
      for(int jResult = 0; jResult < result[iResult].length; jResult++) { 
       result[iResult][jResult] = matrix[iResult][jResult] + matrix1[iResult][jResult]; 

       System.out.print(result[iResult][jResult] + " "); 
      } 

      System.out.print("\n"); 
     } 
    } 
} 

結果是:

3.4000000000000004 0.0 2.3 

8.0 0.0 8.7 

3.5 4.5 2.5 

當我改變數值矩陣[1-10]每次[J0]和Matrix1 [i0] [j0]我得到了正確的結果,但是當值爲1.2和2.2時,我總是得到3.400000000000004。我該如何解決這個問題,爲什麼會發生這種情況。

在此先感謝。

+2

不要使用浮點值。你需要多少小數?使用整數或BigDecimal。例如見http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – 2014-09-12 23:19:57

+0

我需要雙打,它是物理項目和矩陣將填充-10.1和7.7之間的值 – user3151703 2014-09-12 23:27:56

+0

多少精確度你需要?無論是使用BigDecimal,還是使用longs,並在需要顯示它們時將該點放在正確的位置。 – 2014-09-13 00:15:34

回答

0

浮點值是近似值。一些小數值不能完全由它們表示。通常情況下,您可以通過在輸出時將數字格式化爲合理的小數位數來隱藏該數字。或者使用其他號碼類型,如BigDecimal