Search code examples
rmatrixmatrix-multiplication

Why element-wise matrix multiplication giving different output for same numbers in R?


Consider the following matrix A and B.

> A
          [,1]     [,2]     [,3]
 [1,] 76.66894 76.46920 76.38535
 [2,] 76.66894 76.48072 76.40349
 [3,] 76.66894 76.56698 77.22777
 [4,] 76.66894 76.46920 76.38535
 [5,] 76.66894 76.48072 76.40349
 [6,] 76.66894 76.56698 77.22777
 [7,] 76.66894 76.46920 76.38535
 [8,] 76.66894 76.48072 76.40349
 [9,] 76.66894 76.56698 77.22777

> B
           [,1]      [,2]      [,3]
 [1,] 0.1111111 0.1111111 0.1111111
 [2,] 0.1111111 0.1111111 0.1111111
 [3,] 0.1111111 0.1111111 0.1111111
 [4,] 0.1111111 0.1111111 0.1111111
 [5,] 0.1111112 0.1111112 0.1111112
 [6,] 0.1111111 0.1111111 0.1111111
 [7,] 0.1111111 0.1111111 0.1111111
 [8,] 0.1111111 0.1111111 0.1111111
 [9,] 0.1111111 0.1111111 0.1111111

I would like to take element-wise multiplication of A and B and I expect that in the first column all the results would be identical except for the 5th as it will be multiplied with a slightly higher number. However, I get the following result:

C <- A*B
> C
          [,1]     [,2]     [,3]
 [1,] 8.518769 8.496576 8.487259
 [2,] 8.518772 8.497859 8.489277
 [3,] 8.518769 8.507440 8.580862
 [4,] 8.518772 8.496579 8.487262
 [5,] 8.518775 8.497861 8.489280
 [6,] 8.518772 8.507443 8.580865
 [7,] 8.518769 8.496576 8.487259
 [8,] 8.518772 8.497859 8.489277
 [9,] 8.518769 8.507440 8.580862

I am getting a slightly different value even when the same values are being multiplied. Why is this happening?


Solution

  • These are floats, so there must be more precision instead of just the digits printed and that could have added up as difference in the multiplication i.e.

    print(B[5,] - A[5, ], digits = 16)
    

    would give the difference