University of Energy and Natural Resources
CIVL/EENG 208: COMPUTER PROGRAMMING FOR ENGINEERS
MR. EBENEZER K. SIABI
EARTH OBSERVATION RESEARCH AND INNOVATION CENTER
(EORIC)
OUTLINE
INTRODUCTION TO PYTHON
PHILOSOPHY OF PYTHON
PYTHON & ENGINEERING
MODULA PROGRAMMING
INTEGRATED DEVELOPMENT ENVIRONMENTS (IDEs)
VARIABLES & DATA TYPES
OPERATORS
ARRAYS
PLOTTING
FUNCTIONS AND LOOPS
Arrays CIVL/EENG
208
Most often during scientific computation, a series of numbers
needs to be operated upon together. The list data type stores a
sequence of values.
All elements of list can be accessed by their index, but individual
list elements can belong to any data type. Hence, a new kind of
object needs to be defined, similar to list but that stores only
numeric values. This data type is called an array. This data type is
not built in the Python interpreter, but it is within the module
numpy.
CIVL/EENG
208
Arrays Con’t CIVL/EENG
208
The numpy module carries a unique object class called array. It carries
member elements of only one data type. The concept of using arrays to
store numerals gave rise to a powerful idea of array-based computing. The
origins of this method can be traced back to matrix algebra.
A matrix is also a collection of numbers. Similar to matrices, arrays can be
multidimensional and can be operated on by operators defined the same
way as those for mathematical matrices. Using matrices, problems
involving a system of equations even be coupled to each other) in one
instance.
CIVL/EENG
208
Arrays Con’t CIVL/EENG
208
Using the method of indexing of elements, particular elements can be
accessed for operations. Using the concept of slicing, array dimensions can
be altered as per requirements. Using operators acting on this object,
mathematical formulations can be implemented. In this chapter, we will
discuss the use of arrays for mathematical computations.
CIVL/EENG
208
Arrays Con’t CIVL/EENG
208
Numpy
The numpy package contains various items that can be used for numerical
computation—hence, the name numerical Python. NumPy originated from
Numeric, which was originally created by Jim Hugunin with contributions
from several other developers. Travis Oliphant created NumPy in 2005 by
incorporating features of the competing Numarray into Numeric, with
extensive modifications. numpy is released under an open source license.
This chapter’s code has been tested for version 1.12.1.
CIVL/EENG
208
Arrays Con’t CIVL/EENG
208
Numpy
To use, numpy can be imported and the version number can be
checked:
import numpy
print (numpy.version.version)
CIVL/EENG
208
Arrays Con’t CIVL/EENG
208
Numpy
Line 1 imports the whole module named numpy for our use. Line 2 uses the
function version, which further uses the function version to find the installed
version of numpy on the system. Users are encouraged to check their version of
Python.
It is also important to note that importing a module is necessary for its usage, but
once imported in a session, it doesn’t need to be imported each time it is used.
However, if the session is restarted, it must be freshly imported. For this chapter, it
can be imported once and then codes can be written, but if a user shuts down the
Python session and comes back to start it again, it must be imported again.
Arrays Con’t CIVL/EENG
208
ndarray
ndarray is the main object of numpy, which is homogeneous (containing only one
data type for all its member elements). The elements are created using the array()
function of numpy. This functions needs a list as input.
a = [1,2,3]
a
type(a)
import numpy
b = numpy.array([1,2,3])
b
type(b)
Arrays Con’t CIVL/EENG
208
ndarray
b.dtype
c = numpy.array([1.0, 2.0, 3.0])
c.dtype
This example shows how lists and arrays in numpy are created differently. The
numpy object array takes a list as input. The data type of elements can be assigned
by the Python interpreter at the time of interpretation in a dynamic fashion.
Alternatively, the data type can be defined at the time of creation too using the
second argument of the array() function:
a1 = numpy.array([1,2,3], dtype=float)
a1
Arrays Con’t CIVL/EENG
208
ndarray
a2 = numpy.array([1,2,3], dtype=complex)
a2
a2.dtype
ndarray is also known by its alias array. Apart from knowing the data type by using
dtype, there are a variety of methods to get information about various attributes of
ndarray, as shown below
Arrays Con’t CIVL/EENG
208
ndarray
Various Methods to Probe the Property of an Array
ndarray.dtype Data type of elements
ndarray.ndim Dimension of array
ndarray.shape Shape of array, (n, m) for (n, m) array
ndarray.size Size of array, n × m
ndarray.itemsize Size in bytes of each element
ndarray.data Buffer data containing actual element
ndarray.reshape Reshapes keeping n × m constant
Arrays Con’t CIVL/EENG
208
ndarray
Table above can be understood using the following Python code. We first define a 3
array named a3 and then probe the property of this object using the methods listed:
a3 = numpy.array( [ (1,2,3), (4,5,6), (2,7,8) ] ) #defining array
a3 # REPL prints contents of a3
a3.ndim # number if dimesnions of a3-2 i.e it can be described in terms of rows and
columns
a3.size # total number of elements
a3.shape # number of elements in each dimesnion as a tuple
a3.dtype # data type of member elements
a3.data # address of memory location whre array is stored
Arrays Con’t CIVL/EENG
208
ndarray
a3.itemsize # Size in bytes of each element
a3.reshape(1,9) # reshaping 3 X 3 array as 1 X 9 array i.e 1 row and 9 columns
a3.reshape(9,1) # reshaping 3 X 3 array as 9 X 1 array i.e 9 row and 1 columns
a3.reshape(9,1) is a3.reshape(1,9)
Automatic Creation of Arrays CIVL/EENG
208
Various functions exist to automatically create an array of the desired dimensions and
shape. This comes in handy during mathematical calculations where creating arrays
by hand is a tiresome task. During the initialization to zero values for matrix
computations, the zeros() function is extensively used.
zeros()
To create an array where all elements are 0, we use the zeros() function:
numpy.zeros((3,4)) # arrays of float type by default
numpy.zeros((3,4),dtype=int) # array of int data type
numpy.zeros((3,4),dtype=complex) # array of complex
numpy.zeros((3,4),dtype=str) # array of empty strings
Automatic Creation of Arrays CIVL/EENG
208
ones()
To create an array where all elements are 1, we use the ones() function:
numpy.ones((3,4)) # array of float values
numpy.ones((3,4),dtype=int) # array of int values
numpy.ones((3,4),dtype=complex) # array of complex
numpy.ones((3,4),dtype=str) # array of empty strings
Automatic Creation of Arrays CIVL/EENG
208
ones_like()
Taking its cue from an existing array, ones_like() creates a ones array of
similar shape and type:
a = numpy.array([[1.1, 2.2, 4.1],[2.5,5.2,6.4]])
numpy.ones_like(a)
numpy.ones_like(a,dtype=int)
numpy.ones_like(a,dtype=complex)
numpy.ones_like(a,dtype=str)
Automatic Creation of Arrays CIVL/EENG
208
empty()
empty() returns an array of uninitialized (arbitrary) data of the given
shape, dtype, and order. Object arrays will be initialized to None. Unlike
zeros, it does not always set the array values to 0 value:
numpy.empty((2,2))
numpy.empty((2,2),dtype=int)
numpy.empty((2,2),dtype=complex)
numpy.empty((2,2),dtype=str)
Automatic Creation of Arrays CIVL/EENG
208
empty_like()
Taking its cue from an existing array, empty_like() creates an empty array
of similar shape and type:
a = numpy.array([[1.1, 2.2, 4.1],[2.5,5.2,6.4]])
numpy.empty_like(a)
Automatic Creation of Arrays CIVL/EENG
208
eye()
Similar to an identity matrix, eye() returns a two-dimensional array where diagonal
elements are valued equal to 1. The function takes the second argument as the index of
the diagonal. 0 indicates the central diagonal. A positive number means moving a
designated number of steps in a vertical upward direction. A negative number means
moving a designated number of steps in a vertical downward direction.
numpy.eye(3, k=0)
numpy.eye(3, k=1)
numpy.eye(3, k=-1)
numpy.eye(3, k=-2)
Automatic Creation of Arrays CIVL/EENG
208
eye()
numpy.eye(3, k=2)
numpy.eye(3, k=1,dtype=int)
numpy.eye(3, k=1,dtype=complex)
numpy.eye(3, k=1,dtype=str)
Automatic Creation of Arrays CIVL/EENG
208
identity()
The identity() function generates a two-dimensional identity array
with 1 as diagonal values. An equivalent matrix will be the one with
determinant as 1—hence, the name identity.
numpy.identity(4)
numpy.identity(4,dtype=int)
numpy.identity(4,dtype=complex)
numpy.identity(4,dtype=str)
Automatic Creation of Arrays CIVL/EENG
208
full()
full fills up particular data into all elemental positions:
numpy.full((3,2),10.5,dtype=int)
numpy.full((3,2),10.5)
numpy.full((3,2),10.5,dtype=complex)
numpy.full((3,2),10.5+2j,dtype=complex)
numpy.full((3,2),'a',dtype=str)
Automatic Creation of Arrays CIVL/EENG
208
full_like()
Just like empty_like and ones_like, full_like creates a new matrix
taking shape and data types from an existing array:
numpy.full_like(a,5.0)
numpy.full_like(a,5.0,dtype=int)
numpy.full_like(a,5.0+2.3j,dtype=complex)
numpy.full_like(a,'a',dtype=str)
numpy.full((3,2),'a',dtype=str)
Automatic Creation of Arrays CIVL/EENG
208
Random Numbers
To create a random array (filled up with random numbers), we use the
random function as follows:
numpy.random.rand(4)
numpy.random.rand(4,4)
Note that the function rand() comes inside the subpackage random within numpy. To get
complete details of this wonderful package, we encourage users to explore it using
help(numpy.random) after issuing the command import numpy. The documentation describes
a rich library of functions to create random numbers as per choice. This makes numpy a good
choice for on the properties of the system under study. Normalized distribution of
random numbers must be used for systems following Gaussian statistics.