Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for action – solving a linear system


Solve an example of a linear system with the following steps:

  1. Create A and b:

    A = np.mat("1 -2 1;0 2 -8;-4 5 9")
    print("A\n", A)
    b = np.array([0, 8, -9])
    print("b\n", b)

    A and b appear as follows:

  2. Solve this linear system with the solve() function:

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

    The solution of the linear system is as follows:

    Solution [ 29.  16.   3.]
    
  3. Check whether the solution is correct with the dot() function:

    print("Check\n", 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. Please refer to the solution.py file in this book's code bundle:

from __future__ import print_function
import numpy as np

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

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

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

print("Check\n", np.dot(A , x))