Search code examples
pythonnumpymatrixassertlinear-equation

Assertion Error while solving pair of linear equations


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]

This assert statement given in my assignment due to which the answer is not matching. It throws an error because [2. 3.] is not equal to [2.0000000000000004, 2.9999999999999996] I am not able to resolve this issue. Please help.


Solution

    1. Do not invert matrices to solve linear equations systems, use np.linalg.solve instead.
    2. There will be round-off errors, instead of checking for equality, you would rather check that the norm of your solution and a reference is smaller than a given (small) tolerance. I.e.:

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

    reference_sol would also be an array.