我写了下面的代码...矩阵除了用怪异的结果
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。我该如何解决这个问题,为什么会发生这种情况。
在此先感谢。
不要使用浮点值。你需要多少小数?使用整数或BigDecimal。例如见http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – 2014-09-12 23:19:57
我需要双打,它是物理项目和矩阵将填充-10.1和7.7之间的值 – user3151703 2014-09-12 23:27:56
多少精确度你需要?无论是使用BigDecimal,还是使用longs,并在需要显示它们时将该点放在正确的位置。 – 2014-09-13 00:15:34