0% found this document useful (0 votes)
157 views18 pages

MPR Semester Test 1 2023

The document provides instructions for a semester test with multiple questions. It defines variables and functions to calculate integrals and the surface area of a cylinder. Students are asked to fill in code blocks to compute integral values over specific ranges and define a function to return a string describing an exact integral value.

Uploaded by

tiaangill
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)
157 views18 pages

MPR Semester Test 1 2023

The document provides instructions for a semester test with multiple questions. It defines variables and functions to calculate integrals and the surface area of a cylinder. Students are asked to fill in code blocks to compute integral values over specific ranges and define a function to return a string describing an exact integral value.

Uploaded by

tiaangill
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/ 18

3/6/2020 questions - Jupyter Notebook

MPR213 Semester Test 1


Instructions
Fill in any place that says # INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.
Fill in your code right after this line and only in the same cell as this line.
You may copy cells or insert new cells in order to assist you in debugging your code. All copied or new
cells, however, must be deleted before the file is finally saved as part of the answer to the
assignment. Failing to do so may crash the autograder and result in a zero mark for the whole test.
You may use nbtutor to assist you in debugging your code. All code that refer to nbtutor should,
however, be deleted before the file is finally saved as part of the answer to the assignment. Failing
to do so may crash the autograder and result in a zero mark for the whole test.
Do not rename this notebook otherwise the autograder will not grade it, resulting in a zero mark.
For example, make sure that no space or a version number like (2) is inserted before the .ipynb of the
name of this file.
Regularly save your file during the test (for instance, after completing each question). Before you finally
save your notebook file as answer to the test, make sure everything runs as expected:
First, restart the kernel (in the menubar, select Kernel →
Restart ).versions
Second run all cells (in the menubar, select Cell → Run All ).
If you cannot get an earlier cell in your notebook to work properly, in the sense that Pythons interrupts with
an error, the autograder will actually try to execute and grade the cells lower down in the notebook, so in
such a case ensure that as much as possible of the lower cells run correctly. This the autograder will do
only if your submitted file does not contain new and/or copied cells. If you do have problems with an
erroneous cell that interrupts Python execution early in your notebook file, you can of course test the lower
cells on a cell-by-cell basis.
The questions.pdf version of this notebook file is given to you merely as an aid during the test. The
questions.pdf file will not be marked and no text that you may add to questions.pdf will therefore be
taken into account during marking. The file questions.pdf for instance allows you to scroll up in it while
working further down in the questions.ipynb file, to read information given earlier. This works well if you
place the questions.pdf and questions.ipynb files next to one another on the screen.
Make sure you fill in
your student number (starting with "u", i.e. replace the 12345678 with your own student number)
the name of the computer work station where you start the test, which is indicated on a sticker on the
screen (i.e., replace the AB12CD34 with the computer number) in the first code cell below.
Do not delete the quotation marks where you fill in your student number and the computer number, as
Python needs to read these as strings.

In [ ]:

# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.
STUDENT_NUMBER = "u12345678"
Computer_number = "AB12CD34"

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 1/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

'''
Execute this cell to partly test whether the format you used to enter your student number
and computer number in the cell above is correct.
'''
try:
assert type(STUDENT_NUMBER) == str
except AssertionError:
raise AssertionError("The variable STUDENT_NUMBER is not a string.")

try:
assert len(STUDENT_NUMBER) == 9
except AssertionError:
raise AssertionError("The variable STUDENT_NUMBER is not 9 characters long.")

try:
assert STUDENT_NUMBER[0] == 'u'
except AssertionError:
raise AssertionError("The string variable STUDENT_NUMBER does not start with the charac

try:
assert STUDENT_NUMBER != "u12345678"
except AssertionError:
raise AssertionError("You have not filled in your student number in the cell above.")

try:
assert type(Computer_number) == str
except AssertionError:
raise AssertionError("The variable Computer_number is not a string.")

try:
assert Computer_number != "AB12CD34"
except AssertionError:
raise AssertionError("You have not filled in your computer number in the cell above.")

print("So far so good!")

A a log file needs to be recorded during the semester test. Please execute the following cell at least once. It
may be executed several times, and every time you run the whole notebook it will be executed.

Once this next cell has been executed once, it will have created a log file a1.dat. At fixed time intervals
information is appended to the log file.

If you get an error indicating that "comp3" cannot be found, you are most likely not running the question
notebook in the correct folder, which may cause you to hand in a blank notebook and to get zero for the test.
Therefore, if you get this warning, please get assistance.

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 2/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

# Execute this cell at least once.

from compc3 import compc3

errstr = 'Warning: the variable {} is not defined properly above;\nPlease properly follow t
try:
studnt_nou = int(STUDENT_NUMBER[1:9])
except:
print(errstr.format('STUDENT_NUMBER'))
studnt_nou = 0

compc3(studnt_nou)

Question 1 (7 marks)
Part A (3 marks)
The indefinite integral of𝑓(𝑥) = 𝑥sin(𝑥) is
𝑔(𝑥) = ∫ 𝑓(𝑥) 𝑑𝑥 = −𝑥cos(𝑥) + sin(𝑥) + 𝐶
Use an integration constant 𝐶 of zero, i.e.

𝐶=0
Define the following variables in the next cell: ga , which contains the value of 𝑔(𝑎) at 𝑥 = 𝑎 = 𝜋/4 and gb ,
which contains the value for 𝑔(𝑏) at 𝑥 = 𝑏 = 𝜋/3 .

In [ ]:

# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines


print("ga = ", ga)
print("gb = ", gb)

In [ ]:

"""
Run this cell to partly check your answer.
Note: there may be additional tests that are added during grading.
"""
assert -0.2 < ga and ga < 0.2
assert 0.0 < gb and gb < 1.5
print("All tests passed.")

Part B (1 mark)
Consider once again the integral described in Question 1 above, use the computed values of 𝑔(𝑎) and 𝑔(𝑏) to
calculate the definite integral

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 3/18
3/6/2020 questions - Jupyter Notebook

𝜋/3
∫𝜋/4 𝑓(𝑥) 𝑑𝑥
and store the value in g_exact .

In [ ]:

# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

print("g_exact = ", g_exact)

In [ ]:

"""
Run this cell to partly check your answer.
Note: there may be additional tests that are added after you submit your assignment.
"""
assert 0 < g_exact and g_exact < 1.5
print("All tests passed.")

Part C (3 marks)
Consider once again the indefinite integral

𝑔(𝑥) = ∫ 𝑓(𝑥)𝑑𝑥
as described in Question 1 above and the definite integral g_exact
𝑏
∫𝑎 𝑓(𝑥)𝑑𝑥 = 𝑔(𝑏) − 𝑔(𝑎) .
Assume the numerical values of 𝑔(𝑎) , 𝑔(𝑏) and g_exact are known and passed to the function
exact_string as floating point input parameters in this sequence. The function exact_string must return
exactly the following string:

The exact integral is 0.6 for g(a) equal to 0.3 and g(b) equal to 0.9.

for the case where 𝑔(𝑎) = 0.3 , 𝑔(𝑏) = 0.9 and g_exact = 0.6.
Complete the function exact_string in the next cell so that this result is obtained. This function should also
work for other values of , 𝑔(𝑎) 𝑔(𝑏)
and g_exact .

In [ ]:

def exact_string(ga,gb,g_exact):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.
return string1

# Feel free to change / delete the following lines


print(exact_string(ga=0.3,gb=0.9,g_exact=0.6))
print(exact_string(ga=-0.4,gb=0.8,g_exact=1.2))

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 4/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

"""
Run this cell to partly check your answer.
Note: there may be additional tests that are added during grading.
"""

print(exact_string(ga=0.3,gb=0.9,g_exact=0.6))
print("The exact integral is 0.6 for g(a) equal to 0.3 and g(b) equal to 0.9.")

assert "The exact integral is 0.6 for g(a) equal to 0.3 and g(b) equal to 0.9." == exact_st
print("All tests passed.")

Question 2 (6 marks)
Part A (3 marks)
Write a function area_of_cylinder that calculates and returns the surface area of a cylinder with radius 𝑟
ℎ 𝑟 ℎ
and height . The radius and height of the cylinder should be passed as inputs in this sequence.

Hint: The surface area of a cylinder is given by


𝐴 = 2𝜋𝑟ℎ + 2𝜋𝑟2
In [ ]:

'''
The order of the inputs to the function area_of_cylinder should be
r and then h.
'''
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines


assert (area_of_cylinder(1,1) > 0) & (area_of_cylinder(1,1) < 20)

In [ ]:

"""
Do not delete/change this cell.
"""

Part B (3 marks)
Write the function height_of_cylinder . This function should calculate and return the height of the cylinder ℎ
𝐴 𝑟 𝐴 𝑟
based on a given surface area and radius . The surface area and the radius should be passed to the
function in this order.

Hint: The surface area of a cylinder is given by


𝐴 = 2𝜋𝑟ℎ + 2𝜋𝑟2

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 5/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

# Reminder: The surface area A and the radius r should be passed to the function in this or

# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

h = height_of_cylinder(10,1)
assert (h > 0) & (h < 1)

In [ ]:

"""
Do not delete/change this cell.
"""

Question 3 (2 marks)
Consider the following code:

k = 10
def func(K):
for n in range(k): # What will the value of k be here?
... # Calculations were replaced with an ellips for brevity's sake.
k = 11
func(1)
k = 12

𝑘
What value of (just the number) will be used in the range function? Return the value of 𝑘 in the function
my_answer() as a number.

In [ ]:

def my_answer():
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.
return "?" # replace the "?" with the number for k

# Feel free to change / delete the following lines


print("Your answer is:",my_answer())

In [ ]:

"""
Do not delete/change this cell.
"""
assert (my_answer() > 0) & (my_answer() < 15)
print("All tests passed.")

Question 4 (3 marks)
Complete the function array_length(arr) . This function should return the length of an array or list, denoted
by arr , that was supplied as the input to the function.

For example, if the following


[1,2,1,2,3,4]
localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 6/18
3/6/2020
[1,2,1,2,3,4]
questions - Jupyter Notebook

is supplied to the function as an input, the answer should be 6.

In [ ]:

def array_length(arr):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines


A = [1,2,1,2,3,4]
assert (array_length(A) == 6)

In [ ]:

"""
Do not delete/change this cell.
"""

Question 5 (4 marks)
Write a function angle_degrees(x,y) that calculates the counterclockwise angle of a line between the
point (x,y) and (0,0) in a cartesian plane.

For example,

x=1

y=1

should return 45 degrees.

x=1

y = -1

should return 315 degrees. Partial marks will be awarded for the different quadrants of the cartesian plane.

Reminder: 𝜋 radians is equal to 180 degrees


(Hint: Use the numpy function arctan2 in the calculation.)

In [ ]:

def angle_degrees(x,y):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines


import nbtest
nbtest.validate(angle_degrees(1,1),45.0)
nbtest.validate(angle_degrees(1,-1),315.0)

In [ ]:

"""
Do not delete/change this cell.
"""

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 7/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

Question 6 (6 marks)
Instructions
The objective is to determine whether a beam will plastically deform under a specific moment 𝑀 . A material
𝑌
deforms plastically if the stress exceeds its yield strength .

The rectangular beam under consideration has a width of 𝑤 and a height of ℎ , which results in a moment of

𝐼 = 121 𝑤ℎ3
inertia of

This moment of inertia is calculated by the moment_of_inertia function, which has two inputs w and h
respectively.

The stress in the beam is calculated with

𝜎 = 𝑀𝑦
𝐼
where 𝑀 is the moment. The maximum stress in the beam occurs when 𝑦 = 0.5ℎ.
In [ ]:

# This function is defined here for later calculations. Run this cell.
def moment_of_inertia(w,h):
return 1/12.0 * w * h **3

Part A (3 marks)
Write a function stress_function that has four inputs in this sequence: 𝑀 , 𝑦, 𝑤 and ℎ. This function should
𝜎 = 𝑀𝑦
calculate the stress in the beam with

𝐼
The function should use the predefined moment_of_inertia function in the calculation, with 𝑤 and ℎ given
as inputs to the moment_of_inertia function in that sequence.
localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 8/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

print("The stress in the beam is:",stress_function(1,2,3,4))


assert (stress_function(1,2,3,4) > 0) and ((stress_function(1,2,3,4) < 100))

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

Part B (3 marks)
Write a function stress_severity_case that determines whether the material deforms plastically or not.
Assume the maximum stress, denoted max_stress, in the beam is always positive.

The function has two inputs in this order: max_stress and the yield strength denoted by 𝑌 . If the material
deforms plastically, i.e.
max_stress > 𝑌
the function should return a 2.

If the material is close to yielding, i.e.


0.8 × 𝑌 ≤ max_stress < 𝑌
it should return a 1. Otherwise, the function should return 0.

The function will be partially marked for each case.

In [ ]:

# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change the following lines of code:


stress = 200
yield_stress = 1000
print("Case 1: ",stress_severity_case(stress,yield_stress))
assert stress_severity_case(stress,yield_stress) in [0,1,2]

print("Case 2: ",stress_severity_case(500,200))
assert stress_severity_case(500,200) in [0,1,2]

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 9/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

Question 7 (5 marks)
Part A (3 marks)
Write a function sum_of_first_N_elem(N) that calculates and returns the sum of the first 𝑁 terms of the
1 − 13 + 16 − 121 + 241 + …
following series:

The function sum_of_first_N_elem(1) should return 1.0 and sum_of_first_N_elem(2) should return
0.666666667, i.e. 1 - 1/3.

In [ ]:

def sum_of_first_N_elem(N):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# The following are some tests:


output1 = sum_of_first_N_elem(1)
print("N=1:",output1,1.0)
output1 = sum_of_first_N_elem(2)
print("N=2:",output1,1-1/3)
assert (sum_of_first_N_elem(3) > 0.5) & (sum_of_first_N_elem(3) < 1)

In [ ]:

"""
Do not delete/change this cell.
"""

Part B (2 marks)
Write a function calc_A that returns the answer of the following calculation:

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 10/18
3/6/2020 questions - Jupyter Notebook

𝐾−1 𝑘+2 𝑛 + 0.1𝑘


∑ ∑
𝑘=0 𝑛=1 𝑛 + 2𝑘 + 1
The function has one input 𝐾.
In [ ]:

def calc_A(K):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change the following lines of code:


answer = calc_A(2)
print(answer)
assert (answer > 0) & (answer < 100)

In [ ]:

"""
Do not delete/change this cell.
"""

Question 8 (3 marks)
Write a function find_even(my_array) that returns a list of even values in my_array in the same order as
in my_array . You may assume that the length of the input array is always 10.

For example,

array = np.array([1,2,1,4,5,3,3,3,1,1])

should return

[2,4]

In [ ]:

def find_even(my_array):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

array = np.array([1,2,1,4,5,3,3,3,1,1])

answer_returned = find_even(array)

print("Your function returns: ",answer_returned)

In [ ]:

"""
Do not delete/change this cell.
"""

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 11/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

"""
Do not delete/change this cell.
"""

Question 9 (3 marks)
Consider the following equation:
𝑇𝑛+1 = 𝑇𝑛 − 2 ⋅ 𝑇𝑛−1 + 𝑇𝑛−2 , 𝑛 = 2,3,…𝑁 − 1,and 𝑁 ≥ 3
Complete the function called ts_function . This function should take exactly four inputs in this sequence:

N, is the indice of the last element 𝑇𝑁 that needs to be calculated.


T2, where 𝑇2 = T2
T1, where 𝑇1 = T1
T0, where 𝑇0 = T0

The function should return an array with the following elements 𝑇0 , 𝑇1 , 𝑇2 ,..., 𝑇𝑁 .
For example,

series_function(3,1,2,3)

should return an array with the following elements [3,2,1,0] and


series_function(4,1,2,3)

should return an array with the following elements [3,2,1,0,0].


In [ ]:

def ts_function(N,T2,T1,T0):
import numpy as np
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

print("Your printed answer:",ts_function(3,1,2,3),", Correct printed answer: [3. 2. 1. 0.]"


print("Your printed answer:",ts_function(4,1,2,3),", Correct printed answer: [3. 2. 1. 0. 0

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

Question 10 (6 marks)
The trapezodial rule is a technique for approximating the definite integral :

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 12/18
3/6/2020 questions - Jupyter Notebook

𝑏
∫𝑎 𝑓(𝑥)𝑑𝑥
The trapezoidal rule approximates the area under the function as a set of trapezoids. This performed by dividing
𝑥
the -axis into different sub-intervals. If each sub-intervals is the same length, it follows that

𝑏 Δ𝑥 𝑁
∫𝑎 𝑓(𝑥)𝑑𝑥 ≈ 2 ∑𝑘=1
(𝑓(𝑥𝑘−1 ) + 𝑓(𝑥𝑘 ))
where

Δ𝑥 = 𝑏−𝑎𝑁 = 𝑥𝑘 − 𝑥𝑘−1
𝑁: is the number of sub-intervals
This figure illustrates how the sub-intervals and trapezoids are related to the function. The [𝑥𝑖 , 𝑥𝑖+1 ] is a sub-
inerval.
y

f(xi+1)

f(xi)
Si
f p

x
xi xi+1
In this question, we are going to use the trapezoidal rule to approximate the area under a root function, i.e.
𝑏 𝑏 1
∫𝑎 𝑓(𝑥)𝑑𝑥 = 𝑓(𝑥) = ∫𝑎 √⎯⎯𝑥 𝑑𝑥
Part A (1 Mark):
Compute the analytical or actual value of the integral for 𝑓(𝑥) = 1/√⎯⎯𝑥 and store the value in the variable
act_val . The analytical or actual value of the integral can be calculated with

𝑏 𝑏 1⎯⎯ 𝑑𝑥 = 2(√⎯𝑏 − √⎯⎯𝑎)


∫𝑎 𝑓(𝑥)𝑑𝑥 = ∫𝑎 √𝑥
Use the following bounds in your calculation:

𝑎=1
𝑏 = 10

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 13/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines


print("actual integral value = ",act_val)
print("a = ",a)
print("b = ",b)

In [ ]:

"""
Run this cell to partly check your answer.
Note: there may be additional tests that are added after you submit your assignment.
"""
import numpy as np

assert 0.0 < act_val and act_val < 6.0


print("All tests passed.")

Part B (2 marks)
Write a function trapz that calculates the area under a single trapezoid in the subinterval [𝑥𝑘−1 , 𝑥𝑘 ] . The
following equation can be used in this calculation:

Δ𝑥 (𝑓(𝑥𝑘−1 ) + 𝑓(𝑥𝑘 ))
2
𝑓(𝑥) = √1⎯⎯𝑥
where

and the input arguments to the function should be xk1 for 𝑥𝑘−1 and xk for 𝑥𝑘 .

In [ ]:

def trapz(xk1,xk):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines


print(trapz(0.1,1))
print(trapz(1,7))
print(trapz(1.1,1.2))

In [ ]:

"""
Run this cell to partly check your answer.
Note: there may be additional tests that are added after you submit your assignment.
"""

print(trapz(1,3.12))
print(trapz(0.3,1))

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 14/18
3/6/2020 questions - Jupyter Notebook

Part C (2 marks)
To apply the Trapezoidal rule, it is necessary to divide the domain of intergration, denoted [𝑎,𝑏]
, into 𝑁 sub-
intervals (e.g. see the Figure at the start of this question). Thereafter, the area needs to be separately
calculated for each sub-interval.

Complete the function trapz_terms(a,b,N) so that it returns an array with 𝑁


values, where the first element
in the array is the area under curve in the first sub-interval, the second element in the array is the area under
the curve for the second sub-interval and so forth.

The function should take the bounds of the integral a and b as input arguments, together with the number of

𝑓(𝑥) = √1⎯⎯𝑥
subintervals N to compute the terms for the function:

For example, if 𝑎=1 𝑏=3 𝑁=2


, and [1,2] and [2,3] with the
it means that there will be two sub-intervals

Δ𝑥 (𝑓(1) + 𝑓(2)) = 0.85355339


area under the trapezoids in the two sub-intervals being

2
Δ𝑥 (𝑓(2) + 𝑓(3)) = 0.64222853
and

2
respectively. Therefore, the function trapz_terms(1,3,2) should return an array with the following elements
[0.85355339,0.64222853]
You may use the function trapz in Part B to compute terms of the array.

In [ ]:

def trapz_terms(a,b,N):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines


print(trapz_terms(1,3,2))
print(trapz_terms(1,15,5))

In [ ]:

"""
Run this cell to partly check your answer.
Note: there may be additional tests that are added after you submit your assignment.
"""

print(trapz_terms(1,20,2))
print("All tests passed.")

Part D (1 mark)
Complete a function trapezoidal that calculates the sum of the elements in the array returned by the
trapz_terms function. The function has three inputs , and . 𝑎𝑏 𝑁

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 15/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

'''
If you could not get the trapz_terms working in the previous question, uncomment the two co

and use that trapz_terms in your calculation:


'''

# import numpy as np
# def trapz_terms(a,b,N): # Uncomment this here if you could not complete the previous ques
# return np.ones(N) # Uncomment this here if you could not complete the previous ques

def trapezoidal(a,b,N):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

print("Calculated answer:",trapezoidal(1,10,10))
assert (trapezoidal(1,10,10) > 0) & (trapezoidal(1,10,10) < 1000)

In [ ]:

"""
Do not delete/change this cell.
"""

Question 11 (5 Marks)
Consider the Taylor series expansion for 𝑒𝑥 :
∞ 𝑥𝑛 𝑥0 𝑥1 𝑥2 𝑥3 𝑥4 𝑥5
∑ 𝑛! = 0! + 1! + 2! + 3! + 4! + 5! + ⋯
𝑛=0
= 1 + 𝑥 + 𝑥22 + 𝑥63 + 𝑥244 + 120
𝑥5 + ⋯.
Part A (2 Marks)
Write a function named Taylor_term , by completing the code in the next cell. The function Taylor_term
takes two input parameters x and n , and calculates the 𝑛𝑡ℎ
term in the expansion:

𝑥𝑛 .
𝑛!
For example,

Taylor_term(4,2)

should return a float 8.0 and


Taylor_term(3,0)

should return a float 1.0.


numpy.math.factorial

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 16/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

def Taylor_term(x,n):
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines


print(Taylor_term(5,2))
print(Taylor_term(7,0))
print(Taylor_term(3.6,5))

assert (Taylor_term(5,2) > 10) & (Taylor_term(5,2) < 15)

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

Part B (3 marks)
Complete the function named Taylor_approx in the next cell. The function Taylor_approx takes exactly
𝑥
two input parameters and tol in that sequence. The Taylor_approx function is used to approximate the
value for
∞ 𝑥𝑛 𝑥0 + 𝑥1 + 𝑥2 + 𝑥3 + 𝑥4 + 𝑥5 + ⋯
=
∑ 𝑛! 0! 1! 2! 3! 4! 5!
𝑛=0
with the calculation terminated when the absolute difference between approximation and actual function value
𝑒𝑥 is smaller than a specified tolerance given by tol . The exact value of the expansion exact_v is supplied
in function definition.

The function named Taylor_approx should return your approximation.

You may use the Taylor_term in this calculation. A correct Taylor_term is generated before marking this
part of the question.

In [ ]:

def Taylor_approx(x,tol):
import numpy as np
exact_v = np.exp(x) # Exact value of the expansion
# INSERT YOUR CODE FOLLOWING THIS LINE; DO NOT ERASE THIS LINE.

# Feel free to change / delete the following lines

# print(Taylor_approx(1,1.0e-3))
# print(Taylor_approx(0.8,1.0e-6))
# print(Taylor_approx(-0.1,1.0e-6))

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 17/18
3/6/2020 questions - Jupyter Notebook

In [ ]:

"""
Do not delete/change this cell.
"""

In [ ]:

"""
Do not delete/change this cell.
"""

localhost:8888/notebooks/Documents/Dept/MPR213/Tests_Exam_2020/SemTest1/assignment/release/ST1/questions.ipynb 18/18

You might also like