What mistake did I make in this matrix multiplication in Julia?

In Julia:

In  [1]: M1 = [1 3 4;
              45 64 33;
              456 3 454;]

Out [1]: 3x3 Array{Int64,2}:
   1   3    4
  45  64   33
 456   3  454

In  [2]: M1 * inv(M1)

Out [2]: 3x3 Array{Float64,2}:
  1.0           6.93889e-18  -8.67362e-19
  0.0           1.0          -2.08167e-17
 -1.42109e-14  -8.88178e-16   1.0        

M1 * inv (M1) should get the Identity matrix by definition. What's wrong?

I tried the same in Matlab:

>> M1 = [1 3 4;
         45 64 33;
        456 3 454;]
M1 =
     1     3     4
    45    64    33
   456     3   454
>> inv(M1)
ans =
  -0.280088987764182   0.013057987135465   0.001518595540939
   0.052057842046719   0.013251438796731  -0.001421869710306
   0.280978865406007  -0.013203075881414   0.000686753397495
>> M1 * inv(M1)
ans =
   1.000000000000000   0.000000000000000  -0.000000000000000
                   0   1.000000000000000  -0.000000000000000
  -0.000000000000014  -0.000000000000001   1.000000000000000
>> 

Matlab returns the correct result. I think Julia is not mistaken here. So what happened to my calculations / designation?

Edit

The problem is caused by the number of digits as a result of the floating point. I should have asked how to set the accuracy of the numbers in Julia?

0
source share
1 answer

Julia and Matlab actually give the same result (for example, the lower left element is -1.4e-14 in both cases): this is not exactly the same matrix, because floating point arithmetic is not exact.

You can explicitly round the result before displaying it.

M1 = [
  1    3   4;
  45  64  33;
  456  3 454
]
round( M1 * inv(M1), 6 )
# 3x3 Array{Float64,2}:
#  1.0   0.0  -0.0
#  0.0   1.0  -0.0
#  0.0  -0.0   1.0

, .

M1 = [
  1//1  3   4;
  45   64  33;
  456   3 454
]
M1 * inv(M1)
# 3x3 Array{Rational{Int64},2}:
#  1//1  0//1  0//1
#  0//1  1//1  0//1
#  0//1  0//1  1//1
0

Source: https://habr.com/ru/post/1609726/


All Articles