0% found this document useful (0 votes)
2 views27 pages

W1 - Introduction to Numerical Programming - Course Notes

The ENG1014 course notes introduce students to numerical programming with a focus on Python, covering basic syntax, variables, operators, and the Numpy library for matrix operations. The notes serve as a guide for the course, encouraging exploration of additional resources and study methods. Key topics include programming fundamentals, data types, and practical exercises to reinforce learning.

Uploaded by

p7sjtjkdvd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views27 pages

W1 - Introduction to Numerical Programming - Course Notes

The ENG1014 course notes introduce students to numerical programming with a focus on Python, covering basic syntax, variables, operators, and the Numpy library for matrix operations. The notes serve as a guide for the course, encouraging exploration of additional resources and study methods. Key topics include programming fundamentals, data types, and practical exercises to reinforce learning.

Uploaded by

p7sjtjkdvd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

ENG1014 Engineering Numerical Analysis Course Notes

ENG1014 Course notes


Week 1. Introduction to Numerical Programming

WEEK 1. INTRODUCTION TO NUMERICAL PROGRAMMING .................................................................. 1


INTRODUCTION TO THE ENG1014 COURSE NOTES .................................................................................... 2
INTRODUCTION TO PROGRAMMING IN PYTHON ........................................................................................ 4
1.1. INTRODUCTION TO PROGRAMMING .............................................................................................................. 4
1.2. VARIABLES .............................................................................................................................................. 5
1.3. OPERATORS ............................................................................................................................................ 7
1.4. PYTHON DATA TYPES .............................................................................................................................. 10
1.5. PYTHON COMMENTS............................................................................................................................... 11
1.6. PYTHON BUILT-IN FUNCTIONS .................................................................................................................. 12
1.7. PYTHON MODULES AND PACKAGES ........................................................................................................... 13
MATRICES IN PYTHON - NUMPY .............................................................................................................. 16
1.8. WHAT IS NUMPY? .................................................................................................................................. 16
1.9. ARRAY CREATION IN NUMPY .................................................................................................................... 17
1.10. NUMPY ARRAY ATTRIBUTES ...................................................................................................................... 18
1.11. ARRAY CREATION IN NUMPY (CONTINUED) .................................................................................................. 19
1.12. ADDRESSING NUMPY ARRAYS .................................................................................................................. 20
1.13. WORKING WITH ARRAYS IN NUMPY............................................................................................................ 22
1.14. NUMPY ARRAY ARITHMETIC ...................................................................................................................... 23

Week 1 Overview
In week 1, we will be getting comfortable with the different programming environments that we
will use this semester, and learning many different aspects of basic Python “syntax” – the
grammar rules of how to write commands. We will also introduce the package “Numpy” and its
basic capabilities in working with matrices.

1
ENG1014 Engineering Numerical Analysis Course Notes

Introduction to the ENG1014 Course Notes


These course notes are the central resource that outline what is covered with the ENG1014
syllabus. They are intended to be a reference, not a novel, and we don’t recommend reading
them from start to finish.

• The course notes are the “guide” that will tell you what is included as part of the course.
Now you’re at university, you shouldn’t limit yourself to just learning what is in your units;
if there are topics that you find interesting or that you think will be important, you should
try to learn these as well for your own benefit. The course notes however give you the
limits on what we will examine you on.

• Within the notes, there will be signposts to other resources, such as examples, practice
questions and quiz sections. There may also be clickable links to external resources like
videos or online resources.

• We do not recommend that you just read these notes from start to finish. You should
experiment to work out what study routine works best for you. You may wish to start with
the examples and practice questions in the Jupyter notebooks, or you may skim read the
notes first, make summary notes, etc. There are many possibilities. “Study” means “play
with the material in a variety of ways until you understand it”, not just “read the assigned
document”. You don’t need to do everything; we provide a range of resources and it’s up
to you to choose which of them are useful for you.

• There are often many ways to solve problems with code, particularly with python – it is a
very flexible language. We have made various choices about what to include in the notes,
and what to leave out. We acknowledge that there will be different points of view on what
is important, and other courses will teach things in different ways. If you want to use
other study methods such as the many online courses for learning basic python, that’s
good – they are good resources and university study should encourage exploration. But
we may not always be able to provide support, and in some cases we may require you to
use (or not use) particular methods for your assessments. Some choices we’ve made
are:
o We do not teach any details of object orientation.
o We try to avoid where possible using several types of variables; we don’t teach
tuples, dictionaries or sets, and in most cases we will use numpy arrays rather
than lists. We have avoided any introduction to the “pandas” package and
dataframes.

2
ENG1014 Engineering Numerical Analysis Course Notes

Related Resources

Beyond the course notes document, there are other resources to help your study.
• Course notes examples notebook: these are simply pieces of code that are written to
show you how a particular concept works. For week 1, this is a file called “W1 -
Introduction to Numerical Programming - Course Notes Examples.ipynb”, which can be
opened using JupyterLab.
• Course notes practice questions notebook: this is a similar filetype to the examples,
but they are interactive – you will have to fill in small sections of code to make the code
work correctly. For week 1, this is a file called “W1 - Introduction to Numerical
Programming - Course Notes Practice Questions.ipynb”, which can also be opened
using JupyterLab.
• Weekly quiz: there is a quiz to help you practice each week. Each quiz is worth 0.5% of
your semester mark, so each individual question is only worth a tiny amount. You have
unlimited time to complete the quiz and can close it and come back to it later if you wish
(as long as you don’t “submit”). You can immediately check whether your answer to an
individual question is correct, and often there will be feedback to help you.
• Python resources: a list of useful documents and websites

Examples of signposts used in the notes to help you navigate between the resources:

Complete Practice Question 1 from the W1 - Introduction to Programming – Course Notes


Practice Questions

You should now be able to answer Part A from W1 – Weekly Quiz

Refer to Example 1 from the W1 – Introduction to Python – Course Notes Examples

3
ENG1014 Engineering Numerical Analysis Course Notes

Introduction to Programming in Python

1.1. Introduction to Programming


1.1.1. What is a computer program?
A computer program is a set of instructions that a computer follows to complete a task. Like a
recipe tells you the steps to make a dish, a program tells the computer what steps to take to
complete a task. These instructions, or code, are written in a variety of programming languages
which computers can understand. At its most basic level, a program is an efficient way to
perform lots of calculations. This week, you will learn the Python syntax to perform essentially
all the basic calculations that you should be familiar with on a calculator.

1.1.2. What is programming?


Programming, or coding, is the process of creating a computer program. Programming is as
much about logical thinking and problem-solving as it is about writing code. Learning to program
is like learning a new language, but instead of communicating with people, you're
communicating with computers.

1.1.3. What are programming languages?


Programming languages are a vehicle for communication between humans and computers.
Computers can understand only the binary characters 1 and 0 but using only binary characters
isn't an efficient way to communicate for humans. Programming languages simplify how we can
communicate the set of instructions to computers, acting as an intermediate step where the
instructions can be understood clearly by both humans and computers. In ENG1014, we will be
using Python as our programming language.

4
ENG1014 Engineering Numerical Analysis Course Notes

1.1.4. Elements of a program


There are several terms used to describe the elements of a computer program:

Concept Definition

Syntax The set of “grammar rules” of a programming language that tells a computer
how to interpret code and tell us how to write code so that the computer
understands it correctly.

Operator A symbol that instructs a computer program to perform a particular


computational action ("operation").

Expression A piece of syntax which can be evaluated to some value.

Keyword A special word in a programming language with a defined meaning and


purpose for constructing a statement that cannot be used for any other
meaning or purpose.

Statement An instruction that a computer follows. It is either an expression or a special


structure that uses a keyword.

Script A type of program, where a sequence of statements can be run by the


computer from start to finish.

5
ENG1014 Engineering Numerical Analysis Course Notes

1.2. Variables
1.2.1. What are variables?
Variables are containers for storing data values.
You have used variables in algebra. For example:
The Lecturer's age is twice the age of the Student.
𝐿 = 2 × 𝑆
𝐿 and 𝑆 would be considered variables.
Variables are used all throughout programming.

1.2.2. Creating variables


In Python, variables are created (i.e. defined) the moment you assign an initial value to a name.
Syntax:
variable_name = <value>
Example:
distance = 50
name = "Andrew"

Variable name rules


There is a lot of flexibility in what you can call your variables. Unlike in mathematics, where
variables are typically given just a single letter (or a letter and a subscript), variables in computer
programs can have names that are one or multiple words. However, there are some rules that
you need to follow, as Python will not accept certain variable names.
Variable names:
• must start with a letter or the underscore character (_)
• cannot start with a number
• usually only contain alpha-numeric characters and underscores (A-z, 0-9, _)
• cannot be any of the Python keywords: and, as, assert, break, class, continue, def,
del, elif, else, except, False, finally, for, from, global, if, import, in, is,
lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with,
yield

6
ENG1014 Engineering Numerical Analysis Course Notes

Variable name meanings


Variables should be named in a way that the reader can understand what the variable is
representing. With the sole exception of when x is represented in a formula, it is best to avoid
ambiguous variable meanings.
For example, best practice would be:
building_height = 100
For example, bad practice would be:
a = 100
Creating multiple variables
Python allows you to assign values to multiple variables in one line. For example:
fruit_one, fruit_two, fruit_three = "Orange", "Banana", "Cherry"
Python also allows you to assign the same value to multiple variables in one line. For example:
fruit_one = fruit_two = fruit_three = "Mango"

1.2.3. Using variables


You can call variables by typing the variable name. In Jupyter notebooks, for most data types,
this will print the value to the screen if the variable name is the last line in the code block.
You can also use variables in calculations. For example:
vel = 40
vel_doubled = vel*2
You can't use a variable until you define it. The commands in a script will run in order from the
start to the end. Order matters!
Variables in Python are case sensitive. This means that MONASH, monash, Monash, MONash
are all different variables. So, avoid using similar variables that only differ only in case, and be
careful when calling variables, as this can lead to mistakes.

Complete Practice Questions 1-5 from the W1 - Introduction to Programming Course Notes
Practice Questions

7
ENG1014 Engineering Numerical Analysis Course Notes

1.3. Operators
Operators are used to perform operations on variables and values. There are several groups of
operators; the operators in green you will become familiar with in later weeks, the operators in
grey will not be covered in ENG1014.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators

1.3.1. Arithmetic operators


Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Mathematical example Python code Result

+ Addition 1+2 1 + 2 3

- Subtraction 5–1 5 – 1 4

* Multiplication 6×7 6 * 7 42

/ Division 33 ÷ 7 33 / 7 4.714

% Remainder 33 mod 7 33 % 7 5

** Exponentiation 24 2 ** 4 16

// Floor division 33 ÷ 7, rounded down 33 // 7 4

8
ENG1014 Engineering Numerical Analysis Course Notes

1.3.2. Assignment operators


Assignment operators are used to assign values to variables:

Operator Example Same as

= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x – 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3

1.3.3. Operator precedence


Operator precedence describes the order in which operations are performed. As you would
know from mathematics, the order of operations is standardised. Python has an expanded order
of operations, which is generally consistent with those for mathematics. As with mathematical
operations, if two operators have the same precedence, the expression is evaluation from left
to right.
The precedence order is described below, starting with the highest precedence at the top.
Operators covered in this week are shown in blue; operators shown in green will be covered later
in the course; operators shown in grey are outside the scope of ENG1014.
1. (): parentheses (brackets)
2. **: exponentiation
3. +x, -x, ~x: unary plus, unary minus, and bitwise NOT
4. *, /, //, %: multiplication, division, floor division, and modulus
5. +, -: addition and subtraction
6. <<, >>: bitwise left and right shifts
7. &: bitwise AND
8. ^: bitwise XOR
9. |: bitwise OR
10. ==, !=, >, >=, <=, <, is, is not, in, not in: comparisons, identity, and membership
operators
11. not: logical NOT
12. and: logical AND
13. or: logical OR
14. Assignment operators

9
ENG1014 Engineering Numerical Analysis Course Notes

1.4. Python Data Types


Variables can store data of different types, and different types can do different things. The
Python in-built data types are described below. Data types introduced this week are shown in
blue; data types shown in green will be covered later in the course; data types shown in grey are
outside the scope of ENG1014.
Python has the following data types built-in by default, in these categories:
• Text: str
• Numeric: int, float, complex
• Sequence: list, tuple, range
• Mapping: dict
• Set: set, frozen set
• Boolean: bool
• Binary: bytes, bytearray, memoryview
• None: NoneType

Example Data Type


eg = "Hello World" str (string)
eg = 'Hello World'
eg = 20 int (integer)
eg = 20.5 float
eg = 1.3e5
eg = [1,2,3] list
eg = True bool (Boolean)
eg = None NoneType

1.4.1. Python numbers


There are two numeric types in Python that we will be using in ENG1014:
• int, or integer – a whole number, positive or negative, without decimals
• float, or floating-point – a number, positive or negative, containing one or more decimals,
including scientific numbers with an "e" to indicate the power of 10

1.4.2. Python strings


Strings in Python are created by surrounding text by either single or double quotation marks.
a = "hello world"
b = 'hello world'
We will learn more about using strings in Week 2.

10
ENG1014 Engineering Numerical Analysis Course Notes

1.4.3. Python lists


Lists are used to stored multiple items in a single value and are created using square brackets.
For example:
list1 = ["Orange", "Banana", "Cherry"]
list2 = [1, 2, 3, 4, 5]
A list of lists in Python is a list where each element of the outer list is itself a list. This creates a
two-dimensional structure, often referred to as a matrix or 2D list. In Python, the inner lists can
have different lengths and lists of lists could in fact contain multiple inner lists (e.g. a list of lists
of lists of lists. However, in ENG1014, we will usually only have a list of lists that contain inner
lists of the same length. For example:
list3 = [[1,2,3],[10,20,30],[100,200,300],[1000,2000,3000]]
In ENG1014, we will generally only use lists to create NumPy arrays, which we will learn about
in Section 1.8 onwards.

1.4.4. Python NoneType


The NoneType in Python is a data type that represents the absence of a value (null or no value at
all) and is represented by the keyword None. None is not the same as 0 or an empty string or list.

1.4.5. Type casting


Type casting is the process of converting a value from one data type to another. There are a few
functions that can be used to cast:
• int(<value>) – converts a float (by removing all decimals) or string (provided the string
represents a whole number) to an integer
• float(<value>) – converts an integer or a string (provided the string represents a float
or whole number) to a float
• str(<value>) – converts an integer or float to a string

Refer to Example 1 from the W1 – Introduction to Python – Course Notes Examples

11
ENG1014 Engineering Numerical Analysis Course Notes

1.5. Python Comments


As when doing calculations by hand, it is important not to just write equations; you should also
write "comments" to explain what you are doing and why. The same principle applies to coding.
Comments can be used to explain code, to make code more readable to a person. Comments
are a feature of all programming languages and are not executed when you run the code. In
Python, comments start with a #. For example:
# this is a comment
woodside_height = 100
new_horizons_height = 50 # this is also a comment
Python does not have a syntax for multiline comments. You could insert a # for each line.
Alternatively, you could use a multiline string. Since Python will ignore strings that are not
assigned to a variable, you can add a multiline string in your code and place your comment
inside it. For example:
# this is
# a multiline
# comment with
# many hashes
"""
this is
a multiline
comment with
no hashes
"""

Useful trick: if you want to stop a line of code from running but think you might want to use
that line of code later, you can “comment out” the code.

1.6. Python Built-in Functions


In programming, a function is a group of statements that together perform a task. Built-in
functions are pre-defined functions that are part of a programming language, application, or
tool, and can be used without additional installation or importation.
Here are a few of the built-in functions available in Python that we will be using in ENG1014:

Function Description

print(<message>) Print a specified message to the screen.

type(<data>) Get the data type of any variable or data value (refer to 1.4. Python
Data Types).

12
ENG1014 Engineering Numerical Analysis Course Notes

input(<message>) Get input from a user. An optional message can also be printed. The
input() function always returns a string, so if you want a number to
be inputted, it will need to be converted to a number.

help(<function>) Python is a huge language, and chances are good that you won't
remember every detail of every command you will ever use.
Fortunately, Python has good documentation of its various
functions which you can quickly use to find the details you need.
If you know the name of the built-in function, you can display the
documentation of said function using the help() function.
We will learn more about Python documentation in Week 3.

Refer to Example 2 from the W1 – Introduction to Python – Course Notes Examples

1.7. Python Modules and Packages


Modules are files that contain prewritten function and variable definitions. Modules can be
imported into other programs to allow you to access functions and variables that have already
been written, without needing to clutter your file with all the function and variable definitions
that you would otherwise need. Modules are incredibly useful and allow us to build on code and
functionality that other people have built, instead of having to do all of it ourselves.

Once the module has been imported, its functions and variables can be called by using a dot
operator (.) along with the module name.

Syntax:
import <module>
<module>.<function>
<module>.<variable>
1.7.1. Module aliases
The module being imported can also be renamed using the as keyword. Modules are often
imported under an alias when the module name is too large to use repeatedly.
Syntax:
import <module> as <module alias>
<module alias>.<function>
<module alias>.<variable>
It is common practice in the Python community to abbreviate certain modules with particular
aliases. When we introduce these modules, we will indicate the usual aliases the Python
community uses.

13
ENG1014 Engineering Numerical Analysis Course Notes

1.7.2. Packages and submodules


Packages are essentially folders of related modules. For example, the module name A.B
designates a submodule named B in a package named A. There are two methods to call the
functions and variables in the submodule B.

Method 1: You can choose to import the top-level package, since submodules are imported if
you import the top-level package.
Syntax:
import <package> as <A>
<A>.<B>.<function>

Method 2: You can choose to only import the submodule. Often you don't need all the
functionality in a submodule, so this can reduce clutter in your code. This also allows you to
define an alias specifically for the submodule.
Syntax:
import <package>.<submodule> as <B>
<B>.<function>

Figure 1.1 – General structure of


Python packages Figure 1.2 – Structure of the Python package NumPy

As shown in Figure 1.1, packages can contain submodules, functions, and variables. Figure 1.2
shows the structure of the Python package NumPy (refer to 1.8. What is NumPy?) with a couple
of example submodules, functions, and variables. Essentially, the dot operator means going
inside something (package, module, submodule), to get some attribute of it (submodule,
function, variables). On Figure 1.1 and Figure 1.2, the dot operator is represented by the arrows.

14
ENG1014 Engineering Numerical Analysis Course Notes

We will learn more about modules and packages in Week 3. For now, you just need to know how
to import them and how to use the dot operator to call the functions and variables defined in
modules and packages.

You should now be able to answer Part A from W1 – Weekly Quiz

15
ENG1014 Engineering Numerical Analysis Course Notes

Matrices in Python - NumPy


1.8. What is NumPy?
Matrices are mathematical objects that are generally represented as one-dimensional (1D) or
two-dimensional (2D) arrays of numbers. They are very commonly used in engineering.
Matrices are referred to by their 𝑟 × 𝑐 shape, where:
• 𝑟 is the number of rows
• 𝑐 is the number of columns
The number of rows is always listed first.
In traditional mathematics, matrices with only 1 row or column are known as 1D matrices, or
vectors. Specifically, matrices with only 1 row are known as row vectors, and matrices with only
1 column are known as column vectors. However, there is little difference between working with
1D versus 2D matrices. Some examples of matrices are shown in Figure 1.3.

Figure 1.3 - Examples of different matrix structures. In traditional mathematics, B is a 1×4 row
vector, C is a 4×1 column vector, and D is a 3×4 matrix.
NumPy (Numerical Python) is a Python package used for working with matrices.

NumPy is usually imported under the np alias.


import numpy as np

In NumPy, we refer to a matrix as an "array" or "ndarray". In ENG1014, we will use the terms
"array" and “ndarray” interchangeably. The term "ndarray" is short for "N-dimensional array", as
NumPy allows for arrays with any number of dimensions. In ENG1014, we will mainly use 1D
and 2D arrays.
Unlike traditional mathematics, NumPy treats 1D arrays differently to 2D arrays. As shown in
Figure 1.4, in NumPy, 1D arrays can be visualised like a list, while 2D arrays can be visualised
like a table.

1D array 2D array

Figure 1.4 – Visualisation of 1D and 2D arrays in NumPy

16
ENG1014 Engineering Numerical Analysis Course Notes

While in traditional mathematics row vectors and column vectors are often treated differently,
1D arrays in NumPy do not differentiate between them. Visually, they will always be printed as
a horizontal list.
We will continue to explore the differences between 1D and 2D arrays in NumPy throughout the
rest of the course notes. Note that when we use the terms "array" or "ndarray", we are referring
to both 1D and 2D arrays, and we will specify when we are referring to just one or the other.
It is important to note that arrays can only contain one data type.

1.9. Array Creation in NumPy


1.9.1. Array creation methods
There are several different methods that can be used to create new arrays. If you understand
how each one works, you can save yourself a lot of time.

What do you want to create? Example Recommended methods

A matrix with no specific [1,5, −3,2, −9,2,6] np.array()


pattern in its entries

A vector with all the elements [1, 2, 3, 4, 5, . . . ,56, 57] np.arange()


equally spaced
[7, 5, 3, 1, – 1, – 3] np.linspace()

Special matrices [1,1,1,1] np.ones()

[0,0,0,0] np.zeros()

[1,100000,10000000000] np.logspace()

[0.0231,0.1243,0.4824,0.8321] np.random.rand()

[0,7,4,8,4] np.random.randint()

Joining multiple matrices np.hstack()


np.vstack()

17
ENG1014 Engineering Numerical Analysis Course Notes

1.9.2. Creating arrays with no specific pattern


np.array()
An array can be manually created using the np.array() function. In ENG1014, we will mainly
use lists and lists of lists when manually creating arrays.
Syntax:
np.array(<list>, dtype = <dtype option>)
• list: a list of values will create a 1D array, a list of lists will create a 2D array
• dtype option: desired data type for the array; options are None (default, NumPy infers
the data type from the other input arguments), int64 (for integers), float64 (for floats),
str (for strings); optional

Refer to Example 3 from the W1 – Introduction to Python – Course Notes Examples

Complete Practice Question 6 from the W1 - Introduction to Programming Course Notes


Practice Questions

1.10. NumPy Array Attributes


Number of dimensions
The np.ndim(<ndarray>) function returns the number of dimensions of an array.
Shape
The shape of an array is the number of elements in each direction.
For 2D arrays, the np.shape(<ndarray>) function returns two integers separated by a comma
in a pair of parentheses – the first will be the number of rows, the second number of columns.
For 1D arrays, the np.shape(<ndarray>) function returns one integer followed by a comma in
a pair of parentheses – the number of elements.
Note that the shape of an array includes the parentheses.
Size
The size of an ndarray is the total number of elements. The np.size(<ndarray>) function
returns an integer that indicates the total number of elements.
Length
The length of an ndarray is the number of elements in the largest direction.
The len(<ndarray>) function returns an integer that indicates the number of elements in the
outer direction. For a 1D array, this means the number of elements. For a 2D array, this means
the number of rows.

Refer to Example 4 from the W1 – Introduction to Python – Course Notes Examples

18
ENG1014 Engineering Numerical Analysis Course Notes

1.11. Array Creation in NumPy (continued)


1.11.1. Creating vectors with equally spaced elements
np.arange()
This is most useful to create a vector with equally spaced elements where the spacing between
elements is known.
Syntax:
np.arange(<start>, <stop>, <step>, dtype = <dtype option>)
• start: the starting value of the vector, the array includes this vector; default 0; optional
• stop: the end of the vector, the vector does not include this value in most cases
• step: spacing between values; default 1; optional
• dtype option: desired data type for the array; options are None (default, NumPy infers
the data type from the other input arguments), int64 (for integers), float64 (for floats),
str (for strings); optional
As the start and step have default values, there are three variations when using
np.arange():
• np.arange(stop) – creates vector from 0 to stop-1 with a spacing of 1
• np.arange(start, stop) – creates vector from start to stop-1 with a spacing of 1
• np.arange(start, stop, step) – creates vector from start to stop-step with a
spacing of step
np.linspace()
This is most useful to create a vector with equally spaced elements where the spacing between
elements is not known, but the number of elements required is known.
Syntax:
np.linspace(<start>, <stop>, <num>, dtype = <dtype option>)
• start: the starting value of the vector
• stop: the ending value of the vector
• num: number of values, must be non-negative; default 5; optional
• dtype option: desired data type for the array; options are None (default, NumPy infers
the data type from the other input arguments), int64 (for integers), float64 (for floats),
str (for strings); optional
As num has a default value, there are two variations when using np.linspace():
• np.linspace(start, stop) – creates vector from start to stop with 50 values
• np.linspace(start, stop, num) - creates vector from start to stop with num
values

Refer to Example 5 from the W1 – Introduction to Python – Course Notes Examples

19
ENG1014 Engineering Numerical Analysis Course Notes

1.11.2. Creating special arrays


• np.ones(<shape>) – creates an array of the given shape, filled with ones
• np.zeros(<shape>) – creates an array of the given shape, filled with zeros
• np.logspace(<start>, <stop>, <num>) – creates a 1D array with equally spaced
elements on a log scale from start to stop with num (default 50; optional) elements
• np.random.rand(<shape>) – creates an array with random floats from a uniform
distribution over [0,1)
• np.random.randint(<low>, <high>, <shape>) – creates an array of the given
shape, filled with random integers from low (inclusive) to high (exclusive)
Note: np.ones(), np.zeros(), and np.logspace() all have the optional argument to specify
the desired data type for the array , dtype = <dtype option>.

Complete Practice Questions 7-9 from the W1 - Introduction to Programming Course Notes
Practice Questions

1.12. Addressing NumPy Arrays


After an array has been created, we may want to read or edit different parts of that array. We
might want to refer to numbers within an array to perform calculations or create smaller arrays
from a larger array. All values in an array are assigned an address that gives their location. The
process of selecting particular parts of an array is called "addressing" or "indexing".
1.12.1. Addressing a single element in 1D arrays
Array elements can be accessed by referring to its index number. In Python, indexes in arrays
start at 0, i.e. the first element has index 0, the second has index 1, etc.
Syntax:
arrayName[indexNumberOfElement]
Positive indexing allows you to access an array from the start. However, you can also use
negative indexing to access an array from the end.
1.12.2. Addressing a single element in 2D arrays
2D arrays can be thought of like a table with rows and columns, where the dimension represents
the row, and the index represents the column. Once you understand how to address a 1D array,
the only difference when addressing a 2D array is that two indices are used: a row and a column.
Elements from 2D arrays can be accessed using comma separated integers representing the
row and the column the element.
Syntax:
arrayName[<row number>, <column number>]

Refer to Examples 6 & 7 from the W1 – Introduction to Python – Course Notes Examples

20
ENG1014 Engineering Numerical Analysis Course Notes

1.12.3. Slicing arrays


In python, slicing refers to addressing the elements from one given index to another given index,
excluding the second given index. Essentially, slicing refers to addressing multiple elements in
an array.
Syntax:
arrayName[<start>:<end>:<step>]
• start: the starting index of the slice, the slice includes this value; default 0; optional
• stop: the ending index of the slice, the slice does not include this value; default is the
length of the array in that dimension; optional
• step: spacing between indexes in the slice; default 1; optional
A colon by itself will tell python to return all elements.
Figure 1.5 illustrates some examples of addressing and slicing on 2D arrays.

Figure 1.5 - Examples of 2D array addressing and slicing

Refer to Example 8 from the W1 – Introduction to Python – Course Notes Examples

Complete Practice Questions 10-12 from the W1 - Introduction to Programming Course


Notes Practice Questions

21
ENG1014 Engineering Numerical Analysis Course Notes

1.13. Working with Arrays in NumPy


1.13.1. Transposing 2D arrays
2D arrays can be transposed using the function np.transpose(). Note that since NumPy does
not differentiate between row and column 1D arrays, 1D arrays cannot be transposed.
Syntax:
<ndarray 2> = np.transpose(<ndarray 1>)

Refer to Example 9 from the W1 – Introduction to Python – Course Notes Examples

1.13.2. Appending to 1D arrays


Appending refers to adding on elements to the end of an array. The function np.append() can
append values to the end of a 1D array.
Syntax:
<ndarray 2> = np.append(<ndarray 1>, <value>)

Refer to Example 10 from the W1 – Introduction to Python – Course Notes Examples

1.13.3. Concatenating arrays


Concatenating refers to combining the contents of two or more arrays into a single array. The
functions np.hstack() and np.vstack() can be used to concatenate arrays. np.hstack()
concatenates arrays horizontally (column wise) and np.vstack() concatenates arrays
vertically (row wise). For np.hstack(), all the arrays being concatenated must have the same
number of rows while for np.vstack(), all arrays must have the same number of columns.
Syntax:
<ndarray 3> = np.hstack([<ndarray 1>, <ndarray 2>, <etc.>])
<ndarray 3> = np.vstack([<ndarray 1>, <ndarray 2>, <etc.>])
Note that the arrays being concatenated need to be in a list (i.e. a pair of square brackets).
Since arrays can only contain one data type, NumPy chooses the data type of the resulting array
when the arrays have different data types. If all the arrays are integers or floats, the resulting
array will be floats. If at least one array is strings, the resulting array will contain strings.

Refer to Example 11 from the W1 – Introduction to Python – Course Notes Examples

1.13.4. Appending vs concatenating


np.append() can also be used to concatenate arrays by specifying the dimension ( axis = 0
for vertical, axis = 1 for horizontal). However, there are a few limitations:
• np.append() can only concatenate two arrays (np.hstack() and np.vstack() can
concatenate two or more arrays)
• np.append() cannot concatenate 1D arrays vertically (but np.vstack() can)
• if the dimension is not specified, the result of np.append() will be a flattened 1D array

22
ENG1014 Engineering Numerical Analysis Course Notes

1.13.5. Reshaping arrays


Array reshaping refers to changing the shape of an array with changing its data.
Syntax:
<ndarray 2> = np.reshape(<ndarray 1>, <shape>, order = <order>)
• shape: the new shape of the array, -1 to flatten an array to a 1D array
• order: specifies the order in which the elements of the array should be arranged;
options are 'C' (default, rows then columns) and 'F' (columns then rows); optional

Refer to Example 12 from the W1 – Introduction to Python – Course Notes Examples

1.13.6. Type casting arrays


In 1.4.5. Type casting, we introduced type casting as the process of converting a value from one
data type to another using the functions int(), float(), and str(). However, these three
functions cannot cast types on the elements of an array. np.astype() can be used instead.
Syntax:
<ndarray2> = np.astype(<ndarray 1>, <dtype>)
• dtype: desired data type for the array; options are int (for integers), float (for floats),
str (for strings), bool (for booleans, refer to 4.1.2. Converting values to booleans)

Complete Practice Questions 13-15 from the W1 - Introduction to Programming Course


Notes Practice Questions

1.14. NumPy Array Arithmetic


1.14.1. Simple arithmetic with NumPy arrays
Elementwise matrix arithmetic
You should all be familiar with the basic matrix operations shown in Figure 1.6.

é a b ù é e f ù é a+ e b+ f ù
ê ú+ê ú=ê ú
ë c d û êë g h úû êë c + g d + h úû

é a b ù é e f ù é ae + bg af + bh ù
ê ú´ê ú=ê ú
ë c d û êë g h úû êë ce + dg cf + dh úû
Figure 1.6 – Basic matrix operations
However, often we may have data that is stored in matrices, where we want perform
multiplication, division or exponentiation on corresponding elements between matrices
instead.

23
ENG1014 Engineering Numerical Analysis Course Notes

For example:

Item Sale price per item Number of items sold Total income per item

A $1000 12 ?

B $5 52 ?

C $72 48 ?

D $1750 24 ?

Elementwise or element-by-element operations refer to applying the operation to each element


in each array. Usually, only addition and subtraction are elementwise operations. However, in
python, the standard array operations are all elementwise. For example:
arr1, arr2 = np.array([10,11,12,13,14]), np.array([1,2,3,4,5])

Command Output

print(100 + arr1) [110 111 112 113 114]

print(arr1 + arr2) [11 13 15 17 19]

print(100 - arr1) [90 89 88 87 86]

print(arr1 - arr2) [9 9 9 9 9]

print(arr1 * 2) [20 22 24 26 28]

print(arr1 * arr2) [10 22 36 52 70]

print(arr1 / 2) [5. 5.5 6. 6.5 7. ]

print(arr1 / arr2) [10. 5.5 4. 3.25 2.8 ]

print(arr1 ** 2) [100 121 144 169 196]

print(arr1 ** arr2 [ 10 121 1728 28561 537824]

print(arr1 % 2) [0 1 0 1 0]

print(arr1 % arr2) [0 1 0 1 4]

print(arr1 // 2) [5 5 6 6 7]

print(arr1 // arr2) [10 5 4 3 2]

24
ENG1014 Engineering Numerical Analysis Course Notes

Traditional matrix arithmetic


While you will use elementwise operations far more than traditional matrix multiplication in
ENG1014, it is still possible to perform traditional matrix multiplication using the @ operator.

Refer to Example 13 from the W1 – Introduction to Python – Course Notes Examples

1.14.2. NumPy array operations


Summation
The function np.sum() can be used to find the summation of an entire array. np.sum() with
axis=0 calculates the summation of each column, np.sum() with axis=1 calculates the
summation of each row.
Average
The function np.mean() can be used to find the average of the entire array. np.mean() with
axis=0 calculates the average of each column, np.mean() with axis=1 calculates the average
of each row.
Maximum and minimum
The functions np.max() and np.min() can be used to find the maximum and minimum values
of an array, respectively. np.max() and np.min() with axis=0 finds the maximum and
minimum values of each column, respectively. np.max() and np.min() with axis=1 finds the
maximum and minimum values of each row, respectively.
The functions np.argmax() and np.argmin() can be used to find the indexes of the maximum
and minimum values of an array, respectively. np.argmax() and np.argmin() with axis = 0
finds the indexes of the maximum and minimum values of each column, respectively.
np.argmax() and np.argmin() with axis = 1 finds the indexes of the maximum values of
each row, respectively.

Refer to Example 14 from the W1 – Introduction to Python – Course Notes Examples

1.14.3. NumPy logarithms and exponentials


There are several functions in NumPy that can be used to calculate the logarithm of a value.

Function Description Example

np.log2(x) log2(x) print(np.log2(num))

np.log10(x) log10(x) print(np.log10(num))

np.log(x) loge(x) print(np.log(num))

np.exp(x) ex, same as np.e**x (see below) print(np.exp(num))

25
ENG1014 Engineering Numerical Analysis Course Notes

1.14.4. NumPy trigonometry


There are several functions in NumPy related to trigonometry.

np.Function Description Example

np.cos(x) cos(x) where x is in radians print(cos(num))

np.sin(x) sin(x) where x is in radians print(sin(num))

np.tan(x) tan(x) where x is in radians print(tan(num))

np.deg2rad(x) convert x from degrees to radians print(deg2rad(num))

np.rad2deg(x) convert x from radians to degrees print(rad2deg(num))

np.arccos(x) inverse of cos(x) where x is in radians print(arccos(num))

np.arcsin(x) inverse of sin(x) where x is in radians print(arcsin(num))

np.arctan(x) inverse of tan(x) where x is in radians print(arctan(num))

1.14.5. NumPy constants


There are a couple of constants in NumPy that will be used in ENG1014.

Constant Value

np.e e (Euler's number, ~ 2.7183), same as np.exp(1) (see above)

np.pi π (~ 3.1416)

1.14.6. NumPy rounding


There are several functions in NumPy that can be used to round values.

Function Description

np.round(value, decimals) evenly rounds the value to the given number of decimals
using “banker’s rounding” 1

np.ceil(value) rounds up the value to the nearest integer

np.floor(value) rounds down the value to the nearest integer

1
https://medium.com/@nibasnazeem/did-you-know-this-about-the-python-round-function-9323412abf4

26
ENG1014 Engineering Numerical Analysis Course Notes

1.14.7. Other NumPy arithmetic functions

Function Description

np.absolute() absolute value

np.sqrt() non-negative square root

np.sign() indication of the sign (1 if x < 0, 0 if x==0, 1 if x > 0)

You should now be able to answer Part B from W1 – Weekly Quiz

27

You might also like