OOP in C++
Dr Robert Nu ̈rnberg
Driving Test 2016
Wednesday, 23 March 2pm – 4pm
Using the account details given below, attempt all 3 tasks. Write one C++ file per task. Make sure to fill in the answers to each question on the Answer Sheet. Once you have finished, save the 3 files taskN.cpp, N=1. . .3, to a directory or to the Desktop, and contact the invigilator. Do not log off! Hand in your answer sheet and present your files. The invigilator will then reconnect the network cable so that you can email your solutions to robert.nurnberg@imperial.ac.uk with a CC to yourself. You are then free to leave.
Username : ******* Password : *******
1. Linear congruential generator [20 marks]
One of the simplest possible pseudo random number generators is defined by
xn+1 = (a xn + c) mod m ,
for n ≥ 0. Here x0 ∈ N is the seed, and a,c,m ∈ N are natural numbers.
Write a program that implements a linear congruential generator.
2. Real interpolating polynomials [50 marks]
Write a class polynomial that implements polynomials p : R → R of the form p(x) = nk=0akxk, where ak ∈ R, k = 0,…,n, n ∈ N. For polynomials p, q, and α ∈ R, the following operations should be defined: p · q, p + q, α p. You should also be able to return the value of the coefficient ak of xk in p, as well as p(x) for some x ∈ R.
For a continuous function f ∈ C(R) the Lagrange interpolant Ln f ∈ C(R) for the distinct data points {xi}ni=0 ⊂ R is defined by
where
n
(Ln f)(x) = f(xi)φi(x) ∀ x ∈ R,
i=0
φi(x)= n x−xj , i=0,…,n. j=0,j̸=i xi − xj
It can be shown that (Ln f)(xi) = f(xi) for i = 0,…,n. Write a program that, given a function f ∈ C(R) and the distinct data points {xi}ni=0, produces the polynomial Ln f.
3. Complex interpolating polynomials [30 marks]
Create a template polynomial
In the special case K = C, for a continuous function g : C → C the Lagrange interpolant Ln g for the distinct data points {zi}ni=0 ⊂ C is defined by
where
n
(Ln g)(z) = g(zi)φi(z) ∀ z ∈ C,
i=0
φi(z)= n z−zj , i=0,…,n. j=0,j̸=i zi − zj
Write a program that, given a function g : C → C and the distinct data points {zi}ni=0, produces the polynomial Ln g.
[Hint: You should include the line #include
OOP in C++ Wednesday, 23 March 2pm – 4pm
Name
CID
1. Leta=21,c=3,m=101.
Answer Sheet A
value
State x2016 if x0 = 23.
Findthesmallestn>0suchthatxn =x0 =99.
Find the average of x111 for x0 = 1,2,…,10.
2. Let (x0,x1,x2,x3,x4) = (−2,−1,0,1,2) and define f(x) = 1 . 1+x4
State the following values to three decimal digits, i.e. 123.456789 ≈ 123.457.
value
coefficient a2 of x2 in φ2
φ2 (1.5)
coefficient a7 of x7 in φ0 φ1 φ2
coefficient a4 of x4 in L4 f
(L4 f)(0.5)
3. Let (z0, z1, z2, z3) = (0, 1, −i, i) and define g(z) = exp(2 z). State the following values to three decimal digits.
value
coefficient a3 of z3 in φ2
φ2(1 + i)
coefficient a2 of z2 in L3 g
(L3 g)(2 − i)