Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

AMATH 301 Winter 2023

Practice Midterm Exam 1

Syntax of some useful Matlab commands:

• np .abs(x) returns the absolute value of x (or the magnitude for complex numbers).

• np .max(x) returns the maximum value of the vector x.

• np .min(x) return the minimum value of the vector x.

•  len(x) returns the length (i.e. number of elements) of the vector x.

• np .shape(A) returns a tuple whose elements contain the dimensions of A.

• np .arange(a,  b+dx,  dx) generates an array of linearly spaced points between a and b with spacing dx.

• np .linspace(a,b,n) generates an array of n linearly spaced points between a and b.

• np .logspace(a,b,n) generates an array of n logarithmically spaced points between a and b.

•  function_name  =  lambda  variable_names:  formula creates an anonymous function. variable_names should be a comma-separated list.

• np .linalg .norm(x) returns the norm of the vector x.

•  A .t returns the transpose of the matrix A.

•  x  =  scipy .optimize .fsolve(fun,x0) finds a root (or zero) of the function fun near the point x0 and saves it to x.

• np .zeros(m,n), return an m × n matrix of 0’s.

• np .ones(m,n) return an m × n matrix of or 1’s.

• np .polyfit(x,  y,  n) returns the coefficients for a polynomial p(x) of degree n that is a best fit to the data. The output is an array of length n + 1 containing the polynomial coefficients in descending powers.

• np .polyval(p,  x) evaluates the polynomial p (defined as a an array whose coefficients are descending powers of a polynomial) at each point in x.

• plt .plot(x,y,LineSpec,value) plots vector y versus vector x. LineSpec and value together specify the line type, marker symbol and color.

• plt .loglog( . . .) is the same as plot( . . .), except logarithmic scales are used for both the x- and y-axes.

•  x,fval  =  scipy .optimize .fminbound(fun,x1,x2) returns a value x that is a local minimizer of the scalar valued function described in fun in the interval x1  < x < x2. It also returns fval which is the value of the function fun at the point x.

•  x,  fval=scipy .optimize .fmin(fun,x0) starts at the point x0 and returns a value x that is a local minimizer of the function described in fun. It also returns fval which is the value of the function fun at the point x.

•  q=np .trapz(x,y) uses the trapezoidal method to approximate the integral of a function with function values given by the vector y and spatial points given by the vector x.

•  q=scipy .integrate .quad(fun,a,b) numerically integrates the function fun, defined by an anonymous func- tion, from a to b using global adaptive quadrature.

•  X,Y  =  np .meshgrid(x,y) returns 2-D grid coordinates based on the coordinates in the vectors x and y.

1. Each number in the Fibonacci sequence is given by the sum of the preceding two numbers. One way you can express this mathematically is to write the difference equation

fk+1 = fk + fk1 ,

for some indices k .

Suppose you want to produce the first 50 elements of the Fibonacci sequence.   You initialize the sequence so that its first two numbers are 0 and 1 and you write the following code

f  =  np .zeros(50);

f[0]  =  0

f[1]  =  1

for  k  in  range(48):

f[k+1]  =  f[k]  +  f[k-1]

However the result is an array full of only zeros.

(a)  (4 points) Which term in the formula inside of the for loop is responsible for this code not working

as planned?

Solution: The formula should be advanced by one, since k + 1 = 1 in the first iteration of the loop, but it should be k + 1 = 2 because f is already defined for k = 1.

(b)  (6 points) Change 1 line of the code above to fix this error and successfully compute the first 50

elements of the Fibonacci sequence.  (You may either rewrite it here or just cross out and write next to the code above).

Solution: Change f[k+1]  = f[k]  + f[k-1] to f[k+2]  = f[k+1]  + f[k].

2.  (12 points) A particle moves through three-dimensional space (R3) along a path (x(t),y(t),z(t)). As- sume that

x  =  lambda  t:  1+t**2

y  =  lambda  t:  np .sin(t)

z  =  lambda  t:  t**3  *  np .cos(t)

are defined in python. The function

P  =  lambda  t:   np .array([x(t),  y(t),  z(t)])

gives the position of the path (x(t),y(t),z(t)).

(a)  (2 points) Which of the following is true of the function P?

⃝  P : R3 → R3

⃝  P : R3 → R

P : R → R3

⃝  P : R → R

⃝  P : R2 → R

⃝  P : R → R2

⃝  P : R2 → R2

⃝  None of these.

(b)  (5 points) We want to visualize the path of the particle in the x-y plane. Assuming that x and y

are defined in python, write a few lines of code that plot y(t) versus x(t) for t values between 0 and 2π with a step size of 0.01.

Solution:

t = np .arange(0,  2*np .pi+0 .01,  0 .01)

plt .plot(x(t),y(t))

(c)  (5 points) Assume that we have created a matrix/table T with 3 columns and 5 rows. The columns are the values of x(t),  y(t), and z(t) evaluated at t = 1, 2, 3, 4, and 5. Write a few lines of code that produce a new matrix S which is the same as T except with the 2nd column equal to all zeros.

Solution:

S =  T

S[:,1]  = np .zeros(5)

3.  (4 points) Numpy has a built-in function called np .diff. Below is a portion of the help file.

numpy .diff(a,  n=1,  axis=-1,  prepend=,  append=)

Calculate  the  n-th  discrete  difference  along  the  given  axis .

The  first  difference  is  given  by  out[i]  =  a[i+1]  -  a[i]  along  the  given  axis, higher  differences  are  calculated  by  using  diff  recursively .

Examples

>>>  x  =  np .array([1,  2,  4,  7,  0])

>>>  np .diff(x)

array([  1,    2,    3,  -7])

Assume that an anonymous function has been defined in python via the anonymous function f. Which of the following pieces of python code will create a vector that approximates the derivative of f at the points x = 0, 0.1, 0.2, ..., 1 using backward differences and ∆x = 0.1?

⃝  dx  =  0 .1

x  =  np .arange(0,  1+dx,  dx)

fprime  =  np .diff(x)/dx

⃝  dx  =  0 .1

x  =  np .arange(0,  1+dx,  dx)

y  =  f(x)

fprime  =  np .diff(y)/dx

dx  =  0 .1

x  =  np .arange(-dx,  1+dx,  dx)

y  =  f(x)

fprime  =  np .diff(y)/dx

⃝  dx  =  0 .1

x  =  np .arange(0,  1,  dx)

y  =  f(x)

fprime  =  np .diff(y)/dx

4. The population of Seattle seems to be increasing year over year, but we’d like to know if the rate of the rate of increase is positive or negative. In other words, we want to calculate the second derivative of the population in the year 2023.

(a)  (5 points) Assume that P(t) is a function that represents the population of Seattle in the year t.

In other words, P(2023) is the population of Seattle in the year 2023 and we would like to find P\\ (2023). Which of the following finite-difference methods could we use and would give the most accurate results for this problem? You may assume that each of the formulas is correct. (Select only one answer).

P(t + ∆t) 2P(t) + P(t t)

∆t2

P\\ (t) = 2P(t) 5P(t + ∆t) + 4P(t + 2∆t) P(t + 3∆t) + O(∆t2 )

P\\ (t) = 2P(t) 5P(t t) + 4P(t 2∆t) P(t 3∆t) + O(∆t2 )

P\\ (t) = P(t + 2∆t) + 16P(t + ∆t) 30P(t) + 16P(t t) P(t 2∆t) + O(∆t4 )

P\\ (t) =                                                    + O(∆t)

⃝  Not enough information given or multiple of the above

(b)  (2 points) What is the order-of accuracy of the method you selected above?

⃝  First-order accurate

Second-order accurate

⃝  Third-order accurate

⃝  Fourth-order accurate

⃝  Fifth-order accurate

⃝  Twelfth-order accurate

5.  (5 points) I would like to estimate the amount of water in my fish tank, which has a fixed width of 0.1 meters.  My fish tank always has a wave in it, so to find the total volume of water in the tank I need to integrate the height of the wave. Suppose I have a way to measure the height of the wave at

16 points and save these to the 1D array h with len(h)  =  16; see the image below.

Which of the following methods would you be able to use to solve this problem using integration with ∆x = 3/16? Select all that apply.

⃝  Forward-difference

The right-rectangle rule

⃝  Simpson’s rule

The trapezoidal rule

⃝  The midpoint rule for integration ⃝  fminbound

6. Suppose we are trying to calculate the derivative of a function f(x) using the usual central-difference formula for first-order derivatives. We don’t know the true derivative at every point, but some special properties of the function allow us to know that f\ (2) = 0.

(a)  (4 points) When we use the central-difference formula with ∆x = 0.4 we find that the central-

difference formula tells us that the derivative at x = 2 is 0.6.  Approximate  what the central- difference formula will give for the derivative at x = 2 when ∆x = 0.05. You should leave any fractions as they are: you should not simplify.

Solution: We are decreasing the error by a factor of 8, going from ∆x = 0.4 to ∆x = 0.05.

Since the central-difference formula is second-order accurate, the new error is approximately

( ) 2 0.6 = = = .

(b)  (5 points) We would like to approximate the derivative of the function at all points in the interval

0 ≤ x 4.  We would like this approximation to be very precise, but since we don’t know the derivative everywhere we will use the error at x = 2 (at which point we do know the derivative) to represent the error of our method. Fill in the missing lines of code in lines 3-6 below to find the largest value of x so that the error at x = 2 is less than 1 × 10 6 . Your answer should be in terms of a x that is a power of 0.2, e.g., 2 × 10 1 , 2 × 10 2 , 2 × 10 3 etc. You should assume that f has already been defined as an anonymous function and you should use centered differences.

1 .      #  f(x)  defined  above  as  anonymous  function .

2 .      for  k  in  range(1,  16+1):

3 .           dx  =  2*10**(-k)

4 .           approx  =  (f(2+dx)  -  f(2-dx))/(2*dx)

5 .           err  =   np .abs(approx  -  0)

6 .            if  err  < 1e-6:

7 .                 break

7. Consider a case where we want to find the maximum of the function g(y) = sin(y) for 0 ≤ y < 2π .

(a)  (2 points) Write a few lines of code to plot the function g(y) for 0 ≤ y 2π .  The plot that is

created by your code should look smooth. Your answer should look like code you would type; do not use symbols that you could not use on a computer.

Solution:

x = np .arange(0,  2*pi+0 .01,  0 .01)

plt .plot(x, np .sin(x))

(b)

(2 points) guess y0 =

Write code to find the maximum of g(y) using scipy .optimize .fminbound with initial

π

4 .

Solution:

f = lambda x:  -np .sin(x)

argmax = scipy .optimize .fminbound(f, pi/4)

top =  -f(argmax)