求解一对线性方程时的断言错误

问题描述 投票:0回答:1
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]我无法解决此问题。请帮助。

python numpy matrix assert linear-equation
1个回答
0
投票
  1. [不求矩阵求线性方程组的解,改为使用np.linalg.solve。
  2. 会有舍入错误,而不是检查相等性,您宁愿检查解决方案和参考的规范是否小于给定的(小)公差。即:

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

reference_sol也将是一个数组。

© www.soinside.com 2019 - 2024. All rights reserved.