0

I wrote the following code...

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");
        }
    }
}

The result is:

3.4000000000000004 0.0 2.3

8.0 0.0 8.7 

3.5 4.5 2.5 

Every time when i change the values for Matrix[i0][j0] and Matrix1[i0][j0] i get proper results, but when the values are 1.2 and 2.2 i always get 3.400000000000004. How can i fix that , and why that happens.

Thanks in advance.

nbro
  • 15,395
  • 32
  • 113
  • 196
  • 2
    Do not use floating point values. How many decimals do you need? Use either integers or BigDecimal. See for example http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – Diego Basch Sep 12 '14 at 23:19
  • I need doubles , it is for physics project and the matrices will be filled with values between -10.1 and 7.7 – user3151703 Sep 12 '14 at 23:27
  • How much precision do you need? Either use BigDecimal, or use longs and put the dot in the right place when you need to display them. – Diego Basch Sep 13 '14 at 00:15

2 Answers2

0

Floating point values are approximations. Some decimal values cannot be exactly represented by them. Generally you can hide that by formatting your numbers to a reasonable number of decimal places when you output them. Or use another number type, like BigDecimal.

khelwood
  • 55,782
  • 14
  • 81
  • 108
0

It happens due to floating point values being used, as others have said - here is a great question that contains explanations about this very thing.

Community
  • 1
  • 1
Ideasthete
  • 1,553
  • 13
  • 22