Time for action – solving a linear system

Let's solve an example of a linear system. To solve a linear system, perform the following steps:

  1. Let's create the matrices A and b.
    A = np.mat("1 -2 1;0 2 -8;-4 5 9")
    print "A
    ", A
    b = np.array([0, 8, -9])
    print "b
    ", b

    The matrices A and b are shown as follows:

    Time for action – solving a linear system
  2. Solve this linear system by calling the solve function.
    x = np.linalg.solve(A, b)
    print "Solution", x

    The following is the solution of the linear system:

    Solution [ 29.  16.   3.]
    
  3. Check whether the solution is correct with the dot function.
    print "Check
    ", np.dot(A , x)

    The result is as expected:

    Check
    [[ 0.  8. -9.]]
    

What just happened?

We solved a linear system using the solve function from the NumPy linalg module and checked the solution with the dot function (see solution.py).

import numpy as np

A = np.mat("1 -2 1;0 2 -8;-4 5 9")
print "A
", A

b = np.array([0, 8, -9])
print "b
", b

x = np.linalg.solve(A, b)
print "Solution", x

print "Check
", np.dot(A , x)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset