python-3.x - numpy.matmul 给出的答案与@不同
问题描述
我正在转换一些 pre python-3.5 代码,并决定使用@
而不是numpy.matmul
为了可读性。但是,我注意到他们并不总是给出相同的答案。这是一个例子:
A = np.array([[-5.30378554e-01, 5.48418433e-01, -6.46479552e-01],
[-7.72981719e-01, 3.13526179e-04, 6.34428218e-01],
[3.48134817e-01, 8.36203996e-01, 4.23751136e-01]])
B = np.array([[0.84927215, 0., 0.],
[0., 0.52771296, 0.],
[0., 0., 0., ]])
C = np.array([[0.59677163, -0.05442458, 0.80056329],
[0.38445308, 0.89512016, -0.22573375],
[0.70431488, -0.44249052, -0.55510602]])
foo = A @ B @ C
bar = np.matmul(A, np.matmul(B, C))
print(foo)
print(bar)
print(np.array_equal(foo, bar))
print(foo - bar)
这段代码的输出是:
[[-0.15754366 0.28356928 -0.42593136]
[-0.39170017 0.0358763 -0.52558461]
[ 0.34609202 0.37890353 0.13708469]]
[[-0.15754366 0.28356928 -0.42593136]
[-0.39170017 0.0358763 -0.52558461]
[ 0.34609202 0.37890353 0.13708469]]
False
[[ 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 6.93889390e-18 -1.11022302e-16]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00]]
您可以看到计算之间存在细微差别。我曾期望 using@
可以完全替代numpy.matmul
,但鉴于上述情况,它们之间肯定存在一些差异。
解决方案
根据PEP 465,@
是左结合的。因此A @ B @ C
等价于np.matmul(np.matmul(A, B), C)
而不是np.matmul(A, np.matmul(B, C))
。
推荐阅读
- deployment - 如何部署 Finder Sync 扩展项目
- javascript - 如何通过url传递文件输入中收集的图像?
- dart - Flutter 错误:_ScaffoldLayout 自定义多子布局委托忘记布局以下子级
- python - Python - 从给出颜色列表中找到最接近颜色的颜色
- ruby-on-rails - 无法使用 Object.delete(params[:id] 删除记录
- java - BigO复杂度方程一般是如何计算的?
- powershell - 创建约会时使用 PowerShell 和 EWS 模拟原始会议组织者
- javascript - 如何在 javascript 中访问父对象的方法?
- bitbucket - [TeamCity]文件名、目录名或卷标语法不正确
- reactjs - 如何使用 Ant Design 表添加空白可编辑行?