NUMERICAL METHODS
(MCSC-202)
   USING PYTHON
             By
       Samir Shrestha
   Department of Mathematics
 Kathmandu University, Dhulikhel
         Lecture-4
Python Packages
                                 Python Packages
 numpy: Multi-dimensional Array Operations
 matplotlib: Plotting Library
 scipy: Scientific Computing
 pandas: DataFrame (data analysis & manipulate)
 seaborn: Statistical Data visualization
                                  Importing Packages
Python Tips
Python Packages should be imported with their commonly
used names:
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import pandas as pd
import seaborn as sns
                                                      References
1. H. Bhasin, Python Basics A Self-Teaching Introduction, 2019
2. H. P. Langtangen, A Primer on Scientific Programming with Python,
   2016
3. Jaan Kiusalaas, Numerical Methods in Engineering with Python 3, 2013
4. Robert Johansson, Numerical Python: Scientific Computing and Data
   Science Applications with Numpy, SciPy and Matplotlib, 2019
5. https://www.javatpoint.com/python-tutorial
NumPy
                                   Outlines
 Introduction to NumPy
 Creating NumPy 1-D, 2-D arrays
 Methods on NumPy arrays
 Arithmetic operation on arrays
 NumPy Linear Algebra
 Random numbers in NumPy
Introducing NumPy
                                                          NumPy
   NumPy stands for numeric python which is a python package for
    the computation and processing of the multidimensional and single
    dimensional array elements
   NumPy performs vectorized computing and hence efficiently
    implements the multidimensional arrays
   It is capable of manipulation and reshaping the data stored in
    multidimensional arrays
   NumPy provides the in-built mathematical functions , functions for
    linear algebra and random number generation
   NumPy doesn't come bundled with Python. It has to be installed
    it separately:
 $ pip install numpy
In Ubuntu: $ sudo apt-get install python-numpy
In Anaconda : NumPy comes pre-installed
If not, $ conda install numpy or
                  NumPy
NumPy Math Functions
                                                                  NumPy
Most commonly used numpy Math function
                 Trigonometic and Hyperbolic Functions
 sin(x), cos(x), tan(x)               Trigonometric functions, element-
                                      wise.
 arcsin(x), arccos(x), arctan(x)
                                      Inverse trigonometric , element-wise.
                                      Convert angles from radians to
 degrees(x)
                                      degrees.
                                      Convert angles from degrees to
 radians(x)
                                      radians.
                                      Convert angles from degrees to
 deg2rad(x)
                                      radians.
                                      Convert angles from radians to
 rad2deg(x)
                                      degrees.
 sinh(x), cosh(x), tanh(x)            Hyperbolic functions, element-wise.
 arcsinh(x), arccosh(x), arctanh(x)   Inverse hyperbolic, element-wise
     To use NumPy functions, we have to import numpy package
                                                                       NumPy
Most commonly used numpy Math function continue...
               Rounding, Exponential and Log functions
 round_(a[, decimals])   Round an array to the given number of decimals
 rint(x)                 Round elements of the array to the nearest integer
 fix(x)                  Round to nearest integer towards zero
 floor(x)                Return the floor of the input, element-wise
 ceil(x)                 Return the ceiling of the input, element-wise
                         Calculate the exponential of all elements in the input
 exp(x)
                         array.
 log(x)                  Natural logarithm, element-wise.
                         Return the base 10 logarithm of the input array,
 log10(x)
                         element-wise.
 log2(x)                 Base-2 logarithm of x.
     To use NumPy functions, we have to import numpy package
                                                                    NumPy
Most commonly used numpy Math function continue...
                              Other Functions
 prod(a[, axis])      Return the product of array elements over a given axis.
 sum(a[, axis])       Sum of array elements over a given axis.
                      Return the cumulative product of elements along a given
 cumprod(a[, axis])
                      axis.
                      Return the cumulative sum of the elements along a given
 cumsum(a[, axis])
                      axis.
                      Return the non-negative square-root of an array, element-
 sqrt(x)
                      wise.
 cbrt(x)              Return the cube-root of an array, element-wise.
 fabs(x)              Compute the absolute values element-wise.
                      Returns an element-wise indication of the sign of a
 sign(x)
                      number.
 pi                   Returns the value of 𝜋
      To use NumPy functions, we have to import numpy package
                   NumPy
Creating NumPy Array
                                                    NumPy
Creating Numpy Array:
Multi-dimensiona array and matrices can be created using
NumPy module
Creating an Array: Arrays can be created in several ways.
One of them is to use the array function to turn a list into
an array after importing numpy module:
Syntax:
numpy.array(list)
                                                               NumPy
Examples: Creating 1-D and 2-D array
1-dimensional array               2-dimensional array
import numpy as np                import numpy as np
a = np.array([3, -1, 0, 2.1])     b = np.array([[3, -1, 0],[1, 3, -6]])
print(a)                          print(b)
print(a.dtype)                    print(b.dtype)
                                  print(b.shape)
Numpy in-built functions creating 1-D and 2-D array
Syntax:                           Examples:
numpy.arange(start, stop, step)   import numpy as np
numpy.linspace(start,stop,num)    np.arange(0, 10, 0.5) # 1-D array
numpy.zeros((dim1, dim2))         np.linspace(-1,1,10) # 1-D array
numpy.ones((dim1, dim2))          np.zeros((3, 2)) # 3x2 zero matrix
numpy.eye(dim)                    np.ones((2, 3)) # 2x3 matrix of 1
                                  np.eye(3) # 3x3 identity matrix
                   NumPy
Methods on NumPy Array
Methods on Array
                                                                                  NumPy
import numpy as np
 a = np.array([3, -2, 1, 0, 5, -4, 6, 8])
 b = np.array([[1, 0, 3, -2], [2, 1, 0, 7], [2, -3, 1, 4]])
                  Description                             Method               Example
Dimensions of the Array                               ndim           a.ndim
Data type of the array                                dtype          a.dtype
The shape and size of the array                       shape, size    a.shape, a.size
Reshaping the array                                   reshape(m,n)   a.reshape(2,4)
maximum, minimum, and sum of the 1- max, min,                        b.max(), b.min(),b.sum()
D array                             sum
maximum, minimum, and sum of the 2- max(axis=1),                     a.max(axis=0),
D array                             min(axis=0),                     a.min(axis=1), a.sum(axis
                                    sum(axis=1)                      =0)
     axis = 0 represents column, axis = 1 represents row and default is axis = 0
                                                                                NumPy
Method and Function on Array Continue ...
import numpy as np
 a = np.array([3, -2, 1, 0, 5, -4, 6, 8])
 b = np.array([[1, 0, 3, -2], [2, 1, 0, 7], [2, -3, 1, 4]])
              Description                          Method                 Example
mean, standard deviation,                     mean, std, var   a.mean(),a.std(),a.var(),
variance of an array                                           b.mean(axis=0),b.var(axis=1)
                   axis = 0 represents column and axis = 1 represents row
                   NumPy
Indexing and Slicing
   NumPy Array
                                                                                        NumPy
Indexing and Slicing 1-D Array
Let us take a 1-D array: Forward index
                                                     0     1      2        3       4
import numpy as np
a = np.array([3, -2, 5, 0, 7])                       3     -2     5        0       7
                                                     -5    -4     -3       -2      -1      Forward index
Indexing:
                Slicing:
a[0] gives 3
                a[:] gives array([3, -2, 5, 0, 7])        Updating:
a[1] gives -2
                a[0:] gives array( [3, -2, 5, 0, 7])      a[0] = 4 gives a =array( [4, -2, 5, 0, 7])
a[2] gives 5
                a[2:4] gives array( [ 5, 0])              a[-1] = 1 gives a =array( [3, -2, 5, 0, 1])
a[-1] gives 7
                a[0:5] gives array( [3, -2, 5, 0, 7]) a[1:3]=[-1, 4] gives a = array( [3, -1, 4, 0, 7])
a[-3] gives 5
                a[0:-1] gives array( [3, -2, 5, 0])
                a[2: ] gives array( [ 0, 7])
                                                                                                 NumPy
Indexing and Slicing 2-D array
Let us take a 2-D array:                                                    0          1         2       3
import numpy as np                                                  0       1          0         3       -2
a=np.array([[1, 0, 3, -2], [2, 1, 0, 7], [2, -3, 1, 4]])
                                                                    1       2          1         0       7
Indexing:                                                           2       2          -3        1       4
                               Slicing:
a[0,0] gives 1
                               a[1,:] gives array([2,1,0,7])
a[1,2] gives 0                                                              Slicing:
a[-1,-1] gives 4                        0      1       2       3
                                                                            a[1:3,2:4] gives
a[-2,1] gives 1                0        1      0       3       -2           array([[0,7],[1,4]])
                               1        2      1       0       7                0           1        2        3
Slicing:
                               2        2     -3       1       4        0       1           0        3        -2
a[: ,0] gives array([1,2,2])
                                                                        1       2           1        0        7
      0          1      2          3
                                                                        2       2           -3       1        4
0     1          0      3          -2
1     2          1      0          7
2     2          -3     1          4
                     NumPy
Arithmetic Operations on
     NumPy Array
                                                                                   NumPy
Arithmetic Operations (+,-,*,/,**) on Arrays
Performs elementwise operations
                                                 Let us take a 2-D arrays:
Let us take a 1-D arrays:                        import numpy as np
import numpy as np                               a2=np.array([[1, 0, 3],[2,1,4],[2,1,5]])
a1=np.array([1, 0, 3, -2])                       b2=np.array([[-2, 1, 2],[5,3,-1],[0,3,2]])
b1=np.array([-2, 1, 2, 3])                       c2=a2+b2
c1=a1+b1                                         d2=a2*b2
d1=a1*b1                                         e2=a2/b2
e1=a1/b1                                         f2=a2%b2
f1=a1%b1
                                                    1      0        3             -2   1   2
a1=      1        0       3       -2
                                           a2=      2      1        4   b2=        5   3   -1
b1=   -2          1       2       3
                                                    2      1        5              0   3   2
a1*b1=       -2       0       6       -6
                                                               -2       0     6
                                                 a2*b2 =       10       3     -4
                                                               0        3     10
                                                                        NumPy
Arithmetic Operations (+,-,*,/,**) on Arrays continue ...
Let us take a 1-D and 2-D arrays:
import numpy as np
a3=np.array([1, -4, 3])
b3=np.array([[-2, 1, 2],[5,3,-1],[0,3,2]])
c3=a3+b3
d3=a3*b3
e3=a3/b3
f2=a3/b3                           -2     1            2
a3=    2        1       4       b3=   5        3       -1
                                      0        3       2
            2       1   4        -2   1   2                 0   2   6
  a3+b3 = 2         1   4   +    5    3   -1       =        7   4   3
            2       1   4        0    3   2                 2   4   6
      a3 expand to 2-D array
                  NumPy
NumPY Linear Algebra
                                                                            NumPy
NumPy Linear Algebra
NumPy provides various functions to perform operation on NumPy
arrays, here are a few:
       Functions                               Defintions
    dot()              Calculates the dot product of two arrays (equivalent to
                       matix multiplication A*B)
    vdot()             Calculates the dot product of two vectors
    cross()            Calculates the vector product of arrays
    inner()            Inner product of two arrays
    outer()            Outer product of two vectors
    matmul             Calculates the matrix multiplication of two arrays
  Example1:                                 Example2:
  # Scalar product                          # Vector product
  import numpy as np                        import numpy as np
  a = np.array([3,1,2])                     a = np.array([3,1,2])
  b = np.array([-2,3,-2])                   b = np.array([-2,3,-2])
  c = np.dot(a,b)                           c = np.cross(a,b)
                                                         NumPy
NumPy Linear Algebra Continue...
                                   Example4:
Example3:                          # Matrix multiplication changing
# Matrix multiplication            array to matrix by using NumPy
import numpy as np                 function mat
A = np.array([[3,1,2],[-1,2,5]])   import numpy as np
B = np.array([[-2,3,-              A = np.array([[3,1,2],[-1,2,5]])
2],[0,1,3],[2,1,-4]])              B = np.array([[-2,3,-
C= np.matmul(A,B)                  2],[0,1,3],[2,1,-4]])
                                   A = np.mat(A)
                                   B = np.mat(B)
                                   C= A*B
                                                                             NumPy
NumPy Linear Algebra linalg Module
NumPy has linalg module to perform operation on NumPy arrays, here
are a few:
       Functions                             Defintions
     linalg.det()      Calculates the determinant of a matrix
     linalg.inv()      Caculate the inverse of the matrix
     linalg.solve()    Solves the linear system of equations
     linalg.eig()      Eigenvalues and eigenvectors of a square array
     linalg.norm()     Compute norm of vector or matrix
     linalg.cond()     Compute condition number of a matrix
Example5:                                    Example6:
# Determinant                                # Inverse of a matrix
import numpy as np                           import numpy as np
A = np.array([[-2,3,-2],[0,1,3],[2,1,-4]])   A = np.array([[-2,3,-2][0,1,3],[2,1,-4]])
Det = np.linalg.det(A)                       A_inv = np.linalg.inv(A)
                                                                         NumPy
NumPy Linear Algebra Continue...
Example7:                                         Example8:
# System of linear equations                      # Norm of a 1-D array
import numpy as np                                import numpy as np
A = np.array([[2,4,2],[-2,-3,1],[2,2,-3]])        v = np.array([[2,4,2,-3]])
b = np.array([16,-5,-3])                          norm = np.linalg.norm(v)
X = np.linalg.solve(A,b)
Example9:                                    Example10:
# Norm of a 2-D array                        # Eigen-value & Eigen-Vector
import numpy as np                           import numpy as np
v=np.array([[2,4,2],[-2,-3,1],[2,2,-3]])     v=np.array([[2,4,2],[-2,-3,1],[2,2,-3]])
norm = np.linalg.norm(v)                     [EinVal, EinVec],= np.linalg.eig(v)
                                                                  NumPy
Matrix Library: NumPY module numpy.matlib
The NumPy numpy.matlib module contains all the function in the
numpy name space that returns matrices instead of ndarray:
         Functions                            Defintions
  matlib.zeros()         Returns zero matix
  matlib.ones()          Returns matrix of ones
  matlib.eye()           Returns matrix with 1s in diagonal and elsewhere 0s
  matlib.identity()      Returns square identiy matrix
  matlib.repmat(a,m,n)   Repeates 0-D to 2-D matrix of size mxn
  matlib.rand()          Returns a matrix of uniformally distributed random
                         values with given shape
  matlib.randn()         Returns a matrix of standard normally distributed
                         random values with given shape
                NumPy
Random Numebrs in
     NumPY
                                                                     NumPy
Random Numbers in NumPy
Numpy offers the random module to work with random numbers
        Functions                               Defintions
 ranom.rand(m,n)            Uniformaly distributed random number on [0,1] of
                            size mxn
 ranom.randn(m,n)           Standard normal ly distributed random number of
                            size mxn
 ranom.randint(L,H,(m,n))   Random intergers from low L to high H (exclusive)
                            of given size mxn
Numpy also offers the random module to generate the random
numbers from various types of distribution. See www.numpy.org
documentation
End of Lecture-4
    Lecture-5
     Matplotlib
                   34