Assignment 3
Assignment 3
For example:
return (a + b)/2
1
Within the program you MUST document the following:
• Loop invariants
Write all your code in a single Python file named <entryNumber> assignment 3.py.
Part 1
Question 1
In this assignment we will work with iteration (loops) and write their loop in-
variants. We already learnt in class how to calculate the value of sin(𝑥) using the
Taylor series expansion. We will apply the same ideas to calculate some more
useful functions.
Implement the following functions using Taylor’s Series expansions to find the
value of the function for a given 𝑥.
𝑥2 𝑥3
1. 𝑒 𝑥 = 1 + 𝑥 + 2! + 3! +...
>>> expn(0, 2)
1
2
𝑥2 𝑥4
2. cos(𝑥) = 1 − 2! + 4! +...
>>> cosine(pi/2, 2)
0.019
1
3. 1−𝑥 = 1 + 𝑥 + 𝑥 2 + 𝑥 3 + . . . for |𝑥 | < 1
Example:
>>> inverse(0.5, 2)
1.75
𝑥2 𝑥3
4. ln(1 + 𝑥) = 𝑥 − 2 + 3 ...
Example:
>>> natural_log(0.5, 2)
0.375
𝑥3 𝑥5 𝑥7
5. tan−1 (𝑥) = 𝑥 − 3 + 5 − 7 ...
Example:
>>> tan_inv(1, 2)
0.866
Instructions:
3
Question 2
Bisection method: The Bisection method is one of the simplest and most reliable
of iterative methods for finding the solutions of nonlinear equations. This method,
also known as binary chopping or half-interval method, relies on the fact that if
𝑓 (𝑥) is real and continuous in the interval 𝑎 < 𝑥 < 𝑏, and 𝑓 (𝑎) and 𝑓 (𝑏) are of
opposite signs, that is, 𝑓 (𝑎) · 𝑓 (𝑏) < 0, then there is at least one real root between
𝑎 and 𝑏 (there may be more than one root in the interval). Let 𝑥 1 = 𝑎 and 𝑥 2 = 𝑏.
Let us also define another point 𝑥 0 , which is the midpoint of 𝑎 and 𝑏, that is,
𝑥1 + 𝑥2
𝑥0 =
2
1. If 𝑓 (𝑥 0 ) = 0, we have a root at 𝑥 0 .
It follows that by testing the sign of the function at midpoint, we can deduce that
which part of the interval contains the root.
Note: While some books suggest finding if two numbers are of opposite sign by
multiplying them and checking if the product is negative, this idea (while correct
mathematically) is not a good idea computationally (where the approximation may
not precisely reflect the true mathematical value).
0 → 𝑓 (𝑥) = cos(𝑥) + 𝑒 −𝑥
1 → 𝑓 (𝑥) = 𝑒 −𝑥 − sin(𝑥)
1
2 → 𝑓 (𝑥) = sin(𝑥) + 1−𝑥
1
3 → 𝑓 (𝑥) = 1−𝑥 − cos(𝑥)
4
For example, if your entry number is 2021CS12345, then your function is 𝑓 (𝑥) =
𝑒 −𝑥 − sin(𝑥)
• Found (type bool): denotes if there is a root of the function in the given
interval
• Value (type float): the root of the function in the given interval, if it exists
Analysis: Write down the time complexity of the bisection method using com-
ments in the code.
Note: Copying from the internet or from each other will lead to a straight 0 in the
entire assignment and lead to a grade down or an F grade.
Related Links
Moodle course: Here