首页 > 解决方案 > 求解线性方程组时的断言错误

问题描述

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] 我无法解决此问题。请帮忙。

标签: pythonnumpymatrixassertlinear-equation

解决方案


  1. 不要反转矩阵来求解线性方程组,请改用 np.linalg.solve。
  2. 会有舍入错误,而不是检查相等性,您宁愿检查解决方案的范数和参考是否小于给定的(小)容差。IE:

    断言 np.linalg.norm(lin_eqn(a, b) - reference_sol) < 1e-12

reference_sol 也将是一个数组。


推荐阅读