python - 求解线性方程组时的断言错误
问题描述
def lin_eqn(a,b):
'''
Solve the system of linear equations
of the form ax = b
Eg.
x + 2*y = 8
3*x + 4*y = 18
Given inputs a and b represent coefficients and constant of linear equation respectively
coefficients:
a = np.array([[1, 2], [3, 4]])
constants:
b = np.array([8, 18])
Desired Output: [2,3]
'''
# YOUR CODE HERE
**inv=np.linalg.inv(a)
return np.matmul(inv,b)**
print(lin_eqn(np.array([[1, 2], [3, 4]]),np.array([8, 18])))
#It prints [2. 3.]
assert lin_eqn(np.array([[1, 2], [3, 4]]),np.array([8, 18])).tolist() == [2.0000000000000004, 2.9999999999999996]
由于答案不匹配,我在作业中给出了这个断言语句。它会引发错误,因为 [2. 3.] 不等于 [2.0000000000000004, 2.9999999999999996] 我无法解决此问题。请帮忙。
解决方案
- 不要反转矩阵来求解线性方程组,请改用 np.linalg.solve。
会有舍入错误,而不是检查相等性,您宁愿检查解决方案的范数和参考是否小于给定的(小)容差。IE:
断言 np.linalg.norm(lin_eqn(a, b) - reference_sol) < 1e-12
reference_sol 也将是一个数组。
推荐阅读
- c# - 全局更改所有控件的鼠标悬停颜色 WPF
- javascript - 我可以显示来自 firestore 集合的数据,但无法访问数组元素
- python - Chrome 驱动和版本 Chrome version83
- reactjs - 如何在 react-native 中重新渲染 2 次
- javascript - 将 jQuery 转换为 Vanilla JS
- javascript - 迷失在 inputshape 上(Tensorflow.js LSTM 模型尝试)
- azure - Azure redis 缓存补丁计划配置中的 maintenanceWindow 属性是什么?
- django - 未找到“登录”的反向。无论我尝试访问什么 url,“登录”都不是有效的视图函数或模式名称错误
- flutter - 转换流
- > 列出
飘飘然 - blazor - EditForm - 如何防止按回车键提交