Engineer 1D04
Engineering Computation
Term 2, Summer 2019
Important Notice:
This document does NOT contain
full record of lecture material. In the
classroom, these slides are
accompanied by writings and
drawings on the board, as well as
verbal explanations. If you miss a
class, it is your responsibility to
consult with a colleague who
attended the class to obtain as much
information as possible about the
presented material.
A Bokhari, Eng 1D04, Summer 2019 1
Material tested in the midterm and
the final may include any material
presented in class, regardless of
whether it appears in these slides or
not.
A Bokhari, Eng 1D04, Summer 2019 2
What is an Algorithm
• A sequence of steps to solve a
problem or perform a calculation
• History:
– Year 825 Jaffar Mohammed Ben
Musa al-Khowarazmi
– Step by step procedures to carryout
different calculations - Beginning of
Arithmetic and Algebra
– Translated in Latin with title, Liber
Algorismi, meaning ”Book of
al-Khowarazmi”
– Arithmetic itself was sometimes
called algorism
– The word got confused with
A Bokhari, Eng 1D04, Summer 2019 3
arithmetic and took the current form
of algorithm
• To learn computation - start learning
how to write algorithms
• An algorithm can be used for solving
any problem not just calculations
• A friend arriving at Pearson Airport
needs to go to your home
• You can write an algorithm for your
friend:
– On arrival call me on my cell phone
– Meet me outside the baggage claim
area
• A more detailed algorithm:
– Come out through the door after the
A Bokhari, Eng 1D04, Summer 2019 4
baggage claim area
– Turn left in the corridor
– Walk for a couple of minutes and
you will see “Rent-a-car” booths
– Rent a suitable car
– Take HW 427 South
– After 5 Km HW 427 merges with
QEW and Gardener Express Way
– Take QEW West for Hamilton
– Drive for about 15 minutes and you
will see Winston Churchill exit
– Go north on Winston Churchill
– My house number is 244
• Algorithm to fry an egg:
• An algorithm may get complex
A Bokhari, Eng 1D04, Summer 2019 5
• Sometime you may need to select
alternative steps depending upon a
specific situation
– Check if you have an egg
– If yes, put the frying pan on the
stove
– Check if you have oil
– If no, do you want to go and buy oil
from a grocery store?
∗ If no, quit
∗ If yes, go to a grocery store and
buy the oil
– If yes, put the oil into the pan and
switch on the stove
– Break the egg and put it in the pan
– Wait until the egg is cooked
A Bokhari, Eng 1D04, Summer 2019 6
– Remove the egg from the pan and
put it in a plate
– Switch off the stove
• Flow chart can assist
A Bokhari, Eng 1D04, Summer 2019 7
Figure 1:
A Bokhari, Eng 1D04, Summer 2019 8
Algorithms in Engineering:
• Algorithms are a fundamental tool in
engineering
• Modern engineering uses automated
algorithms implemented on computers
to solve a variety of problems
• Consider the following problem:
– Want to find roots of a quadratic
equation
ax2 + bx + c = 0
– What are a, b, c?
– What is x?
– Need knowledge ofqMath:
−b ± b2 − 4ac
x=
2a
A Bokhari, Eng 1D04, Summer 2019 9
– Different solutions depending upon
values of constants:
∗ If a = 0, not a quadratic:
−c
x=
b
b=0 ?
∗ Let b2 − 4ac = d
∗ If d < 0, no real roots, use formula
to calculate complex roots
∗ If d = 0, equal roots x = −b/2a
∗ If d > 0, use formula to calculate
real roots
Algorithm can be represented as a
flow chart:
A Bokhari, Eng 1D04, Summer 2019 10
Figure 2:
A Bokhari, Eng 1D04, Summer 2019 11
• Pseudo Code
– Input data are real numbers (“,”,
“?”, “.”, int)
– We need to check for ‘unwanted
inputs
– Solution:
a,b,c = getInputData
if a==0 and b==0
Deal with these special cases
else
Set d = b * b - 4 * a * c;
Check d => Solutions based on mathematical formulae
Print solutions
Test Cases
a = 0, b =0 Error case
a = 0, b = 1, c = 2 : x = -2/1 = -2
a = 0, b = 1, c = i : error
a = 1, b = -4, c = 4 : x = 2
a = 3, b = 0, c = -27: x1 = -3, x2 = 3
And many more .....
• Like to use a computer to implement
this design
• How can it be done?
• Need to learn a programming language
A Bokhari, Eng 1D04, Summer 2019 12
such as Python
Implementing in Python
• How to get user input?
• How to display the results?
• Where to save the user input for later
use in calculations?
• How to distinguish which user data
relates to what?
A Bokhari, Eng 1D04, Summer 2019 13
Continue with implementation ..
• Read the input data:
x = input()
use try - except to reject invalid input
convert input data to float type
• Next we need to handle special cases
based on values of constants
• If the values fulfill certain conditions
one set of actions is taken otherwise
another set of actions (ref pseudo
code).
• Need language support!
if condition:
action
if - else
if - elif - else
• Implement the algorithm using a
A Bokhari, Eng 1D04, Summer 2019 14
“function”
• Set of instructions that perform a
specific task
def solve(x, y, z):
print("This is the solver")
--------
--------
def main():
print("This program calulates roots of a quadratic equation in the fo
print( " ax^2 + bx + c = 0")
----------
----------
• How to calculate and display complex
roots? cmath
Another Algorithm
• Many engineering problems require
programs capable of solving advanced
equations such as those involving
series representations
A Bokhari, Eng 1D04, Summer 2019 15
• Calculate value of π to 10 significant
digits or more
• Why do we need such a high precision?
• Can use the series:
π 2/6 = 1/12 + 1/22 + 1/32 + 1/42 + ....
• Consider the hyperbolic function
arctanh(x), given by:
x3 x5 x7
arctanh(x) = x + + + + ...
3 5 7
where |x| < 1.0
• Math library of languages such as C
does not have a method for it,
although Python has!
• This infinite series can be written in
A Bokhari, Eng 1D04, Summer 2019 16
summation form as follows:
X x(2n−1)
n=∞
arctanh(x) =
n=1 (2n − 1)
• Converging series - each successive
term decreases in value
• How many terms must be calculated
to get a reliable value?
• We may use a large number say 500
but some series converge rapidly
• When the values of terms gets small
enough, they can be ignored
• For six decimal place accuracy, we can
say that values less than 0.000001 can
be ignored
• How to proceed?
Algorithm
A Bokhari, Eng 1D04, Summer 2019 17
• We have two choices:
1. Set a fixed number of terms to be
used in the series.
2. Set a criteria by which the loop can
be terminated.
• Both have deficiencies:
1. The first may be inefficient if series
converges rapidly.
2. The second may execute the loop an
infinite number of times if the series
does not converge.
• We can use both criteria
– Flow diagram - on the white/black
board
Pseudocode:
A Bokhari, Eng 1D04, Summer 2019 18
– Get the value of x for which the
function needs to be calculated
– Check for valid input - empty string
or character
– Check that x is between -1 and 1,
alert the user if it is not
– Continue execution if x is within the
limits
def main():
print("This program calculates arctanh(x) for a \
given x between -1 and 1.")
while(True):
try:
x =float( input("Enter the value of x, between -1 and 1: "
print( abs(x))
if abs(x) > 1:
print("Invalid Input, x must be \
between -1 and 1, try again.")
continue
except:
print("Invalid input, x must be \
between -1 and 1, try again.")
continue
x = float(x)
print("You entered %f" % x)
break
– Get the max number of terms for
A Bokhari, Eng 1D04, Summer 2019 19
which sum is to be calculated
– Check that the input is an integer
– Get the termination criterion -
minimum value for a term that
should be ignored
– Check for valid input
– Check the value is within reasonable
limits - should not be negative or
less than 0.001
– Call a function/method that
calculates the sum of the series
– Display results
– Inside the function/method:
– Use a loop that executes the number
of times specified by the user as the
“Max number of terms” to be
A Bokhari, Eng 1D04, Summer 2019 20
calculated.
– Within the body of the loop
calculate a new term for each
iteration of the loop and add it to a
cumulative sum.
– During each iteration of the loop,
check if the absolute value of the
calculated term is lower than the
value specified by user as “Min value
of single term”. If so, terminate the
loop.
– How to terminate loop? Use break;
statement
– Display the sum to the user
– We could use a “while” or a “for”
– How to calculate power of a number:
A Bokhari, Eng 1D04, Summer 2019 21
use [Link]()
def calculate(x, n, minVal):
sumOfSeries = 0.0
i = 1
while i <= n:
singleTerm = ([Link](x, (2.0*i - 1.0)))/ (2.0*i - 1.0)
sumOfSeries = sumOfSeries + singleTerm
if abs(singleTerm) < minVal:
break
i = i + 1
print(sumOfSeries)
return sumOfSeries
A Bokhari, Eng 1D04, Summer 2019 22
• Ohm’s law (V = RI)
• Power (P) consumed by an appliance
under certain assumptions: P = VI
• If you know two values in above
equations, the third can be calculated
• In Canada the normal voltage for
household appliances is 110 volts
• You are given a file containing a list of
currents required by different
appliances and you are required to
calculate either the power consumed
by each item or its resistance
• Read the file into a list
• Pass this list and the normal voltage
to a method that calculates either the
A Bokhari, Eng 1D04, Summer 2019 23
power or the resistance as required for
each item and inserts the answer in
another list.
• Write the contents of the list
containing results of calculations to an
output file.
A Bokhari, Eng 1D04, Summer 2019 24