我在Julia的矩阵乘法中犯了什么错误? [英] What mistake did I make in this matrix multiplication 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)应该通过定义来获得恒等矩阵.怎么了?
M1 * inv(M1) is supposed to get the Identity matrix by definition. What's wrong?
我在Matlab中尝试过同样的事情:
I tried the same thing 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在这里返回正确的结果.我想朱莉娅在这里不会犯错.那么我的计算/符号出了什么问题?
Matlab returns the right result here. I guess Julia will not make a mistake here. So what's wrong with my calculation / notation?
修改
该问题是由浮点结果中的位数引起的.我应该问过,如何在Julia中设置结果数字的精度?
The problem is caused by number of digits in floating point result. I should have asked, how to set result digits precision in Julia?
推荐答案
Julia和Matlab实际上给出了相同的结果 (例如,在两种情况下,左下元素均为-1.4e-14): 它不是完全相同的单位矩阵,因为浮点算法不精确.
Julia and Matlab actually give the same result (for instance, the bottom-left element is -1.4e-14 in both cases): it is not exactly the identity 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
如果您想要确切的结果,也可以使用有理.
If you want an exact result, you can also use rationals.
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
这篇关于我在Julia的矩阵乘法中犯了什么错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!