SAMPLE written problems in Python for midterm in PSCB57 _________________________________________________________________________ During preparation we encourage the use of computer, to check if your solution works correctly. In the exam the computer will not be used, but the good thing is that we will not subtract many points for trivial mistakes like typos, as opposed to essential algorithmic and coding mistakes, such as disregarding proper indentation, using meaningless lines of code such as: 0 < x < 1, or confused use of lists in places where only arrays can be used, for instance 3*array_name has a completely different result than 3*list_name, even if they initially hold the same numbers. _________________________________________________________________________ Remember that your program(s) need to be richly commented in actual exam. _________________________________________________________________________ Problem 1. Find 4 coding errors (syntax, logical, or just wrong algorithm) in this code, circle and number them from 1 to 4, then separately (in the booklet) write the correct code that works according to the description. Note1: In case you need to adjust indentation of a block of k lines of code by a constant amount, that counts as one error, not k errors. Note2: Write just the code without extensive comments, or any comments at all. Note3: Assume that all functions from modules like numpy have been correctly imported. ''' This function takes as input a 2-dimensional float numpy array A with size NxM, where N is the first array index (row number). If N=1 or M=1, then array A remains unchanged. Otherwise, if any value A[i,j] in the array is negative, then that value is divided by 2.0; but if any value is positive and greater or equal 10 then the value gets divided by 3.0. The function always returns the unmodified or modified array A and the number of items changed. ''' def limits(N,M,A): if (N*M == 1): return(A,0) nchg = 0 for i in range(N,M): for j in range(N,M): if (A[i,j] < 0): A = A/2; nchg = nchg + 1 if (A[i,j] > 9): A /= 3; nchg += 1 return(A,nchg) Problem 2. As in problem 1, mark mistakes and write the correct code. This time there are 6 programming and syntax mistakes. # integrate this function from given x=a to x=b def f(x): f= np.exp(-x*x) return(f) ''' trapezoid rule of integration ''' def trapezoid(a,b,N): sum, h = 0; (b-a)/N for i in range(N+1): x = b - a + h*i # left boundary of x-interval number i sum = sum f[x] sum += (f[a]+f[b])/2 return(sum*h) # integration completed Problem 2. Write a code that declares a square array of integers of size 10x10, and fill it with numbers from 1 to 100. Scan the whole array and replace with zeros all the numbers divisible by integers from 2 to 9. Print the resultant array, and below the number of non-zero numbers in the table. Problem 3. Input from keyboard a floating point value of V, prompted by a message that it is expected to be in units of m/s. Create a table of angles alpha in degrees (from 15 to 75, with step 1 degree) and the corresponding distance (range) that a stone will land at, on an planet identical to Earth, except for the fact that it has no atmosphere. Stone is thrown at initial speed V, and the angle w.r.t. horizon given in the table. In the loop creating the table, detect and store the maximum range and its alpha, then print them with some explanation immediately under the table. Do not integrate Newtonian dynamics equation, find the range as a function of V and alpha on paper. Problem 4. Give a formal proof that expression f'(x) = [f(x+h/2) - f(x-h/2)]/h has second-order accuracy in h, as approximation to df/dx at point x. Derive the main error term explicitly. Problem 5. Write on paper the Taylor expansion around x = 0 (mathematicians call thus sometimes Maclaurin series) of the function f(x) = exp(-x) Write a function Taylor(k) which, given a numpy array of 100 numbers between 0 and 4 x = np.linspace(0,4,100), sums up the first k terms of the Taylor series, for all x. In other words, function Taylor(k) returns polynomial approximation of f(x) up to order k. Function Taylor(k) should use x as a vector (array), it should not iterate over all individual values in x. In the main program, call that function with k = 2, 4, 8, and 16, for each k plotting the Taylor series approximation together with the original function f(x), for comparison Problem 6. Write program finding a zero of function F(y) = y*(2-y) +y**4/128 between 0.1 and 1. Use Secant method if your student number ends in an even integer, and Newton-Raphson gradient method if it ends with an odd integer. Problem 7. There is a cubic room of size 4x4x4 meters. A spider sits at position (2,3,0) at the floor, and needs to get along the shortest route to a point (1,4,1) on the wall. How soon can he get there walking on the floor and on the wall with the same speed equal v = 0.025 m/s? Write a Python code to find out. Apply any method of zero finding you like to the derivative of T(x), a function that given a point (x,4,0) at the bottom of the wall returns the total time of travel on straight line sectors, passing through that point. Derivative dT/dx should be evaluated analytically i.e. on paper first. Hint: use Pythagoras theorem to find the length of paths on the floor and wall, T is a sum of those distances divided by v. Problem 8. Give the formal proof of the second-order convergence of Newton's root finding method (disregarding roundoff error) by showing that |z - x_{n+1}| = |f''(x_n)/f'(x_n)|/2 |z - x_n|**2 + O(|z-x_n|**3) How does that prove that the number of accurate digits doubles asymptotically during iteration? Problem 9. Using composite trapezoid rule, program the integration of the area under the function y = exp(-x*x) + sin(x)**2 function between x=0 and x=1, with step h=0.001. If the step were decreased to h=0.0001, how many times smaller a deviation from exact intergal's value would be? Problem 10. Two vertical towers of the Golden Gate bridge hold two cables from which the bridge truss and roadway are suspended. Each cable has a shape well approximated by a parabola z(x) = H(2x/S)**2, where H = 155 m is the height of the cable attachment to the tower above roadway, and S=1280 m is the horizontal distance between the towers. x=0 corresponds to the middle of the span, where the cable touches the roadway, so x ranges from -640 m to +640 m. Write a code that computes the length of the cable from the integral L = int_-640^+640 sqrt(1+(dz/dx)**2) dx using analytical expression for dz/dx derived from z(x), and the midpoint integration rule with step dx=1 m. Problem 11. Solve problem 10 with the same step size dx = 1 m, by the Pythagoras rule (summation of 1280 straight distances between 1281 points on the cable, whose x coordinates differ by dx.) Compare both results with exact integration of L using Wolfram Alpha site. Problem 12. A big data set of points (x,y) is to be fit by least squares with the following function: y(x) = (a+bx)**3 + c*x*cos(g*x) +exp(d-x*x) +f*sin(k*x)/(k*x) +ln[x**2/(1+h)**2] Show that parameters a,b,c,d,e,f,h can be found via Gauss' Least Squares method using linear algebra, i.e. relatively quickly, provided that g and k are known, but that parameters g and k require a more complicated search in (g,k) plane, for instance by gradient descent method. Will the linear matrix method need to be done once, or in every step of the (g,k) plane search? Problem 13. Implement the least squares method (filling array A and vector b, then calling np.linalg.solve(A,b)) to find the best parameters: a,b,c in a parabola y(x) = ax**2 +bx +c, which fit the following data: (x,y) = (0,1), (1,2), (1.1,3.3), (1.5,2.9), (1.7,3.14), (2.05, 1.4), (3., 1.33) Problem 14. Write a code to integrate the ODE dF/dt = 2*exp(1-F-2F*F) -1 with intial condition F(t=0) = 0, out to time t=40. Use the midpoint method: go half-step along t axis and evaluate dF/dt, then go back to the starting point of the given time step and take full step dt times dF/dt. Time step dt should be input from the keyboard, and final position output to terminal. Problem 15. Write a code to integrate the second-order equation of vertical motion of a particle under acceleration a=-1. [m/s**2], the drag force with constant b=1. [1/m], and time dependent driving force of amplitude c=0.5 [m/s**2]: d^2 z/ dt^2 = a - b (dz/dt)|dz/dt| + c cos(2*t). Initial conditions at t=0 are: dz/dt = 1., z = 0. Use leapfrog scheme in any particular implementation. Use dt=0.001, print out t,z, and dz/dt every 20th time step. Stop integration at t=T=20. Problem 16. Write a function that integrates the Lotka-Volterra equations (https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations) with alpha = 2/3 beta = 4/3 and gamma = delta = 1, from t=0 to t=100, using starting point (x,y) and time step dt. All 4 parameters, dt and x,y, should be input parametars to the function, and the function should use plt.scatter(x,y,s=5) routine to plot the point of size 5 units on the (x,y) plane as the evolution proceeds, every time step. When integration stops, the plot should be displayed. Your function should work quietly, not printing or returning any values otherwise.