You are on page 1of 8

Technical Programming (TPO)

Homework assigments for Spring Season 2013


NOTE! You need to do ONLY 5 problems.

1. Sound travels through air as a result of colliosions of the molecules in the air. The temperature of the air aects the speed of the molecules, which in turn aects the speed of sound. The velocity of sound in dry air can be approximated by the formula
v = 331.3 + 0.61 TC

(1)

where TC is the temperature of the air in degrees Celsius and the velocity (v) is meters/second. Write a program that allows the user to input a starting and an ending temperature. Within this temperature range, the program should output the temperature and the corresponding velocity in one-degree increments. 2. Write a program that nds the temperature that is the same in both Celsius and Fahrenheit. The formula to convert from Celsius TC to Fahrenheit TF is 9 TF = 32 + TF . (2) The program shoul create two integer variables for the temperature in Celsius and Fahrenheit. Initialiase the temperature to 100 degrees Celsisus. In a loop, decrement the Celsius value and compute the corresponding temperature in Fahrenheit until the two values are the same. Since your are working with integer values, the formula may not give an exact result for every possible Celsius temperature. This should not aect your solution to this particular problem. 3. Create with the help of the header le (.h) and separate source code les (.cpp) for function implementations a small mathematical package which contains the functions dened below. Then in a separate le write a main program that uses at least two of the functions. Dene the following functions: (a) factorial: The factorial can be dened by the product n! = 1 2 3 n when n > 0. 1
5

(b) binomial: The binomial coecients can be dened for nonnegative integers n and k in the following way:
n n! binom( ) = . k k! (n k)!

(3)

(c) exp: The exponential function can be calculated from the following Taylor- series:
ex = 1 + x2 x3 x4 x + + + + 1! 2! 3! 4!

(4)

Exclude the terms that are less than 107 from the sum. (d) log: The logarithmic function can be calculated from the following Taylor- series:
log(x) = (x 1) (x 1)2 (x 1)3 (x 1)4 + + 2 3 4

(5)

Exclude the terms that are less than 107 from the sum. (e) root. To calculate the square root of a number x ( x) we can use Newton's method as follows. Start by guessing a number g 0. We know that there must be a number h such that g h = x or h = x/g . A new better guess is the mean of g and h:
gnew = g + x/g . 2

(6)

Use x/2 for the rst guess and let the guesses continue until the dirence between two consecutive guesses is less than 107 . (f) qcd: A recursive function that will calculate the greatest common divisor of two positive integers m and n is based on the following algorithm:
= m if m=n gcd(m, n) = gcd(m n, n) m > n = gcd(m, n m) otherwise.

(7) (8) (9)

4. Hexadecimal numbers are integers written in base 16. The 16 digits used are '0' through '9' plus 'a' through 'f'. For example, the hexadecimal number d is same as base 10 number 13 and the hexadecimal 1d is the same as the base 10 number 29. Write a C++ program to perform addition and multiplication of two hexadecimal numbers each with up to 10 digits. If the result of the addition or multiplication is more than 10 digits long, then simply give the output message "Addition/Multiplication Overow"and not the result of the operation. Include a loop to repeat this calculation for new numbers until the user says he wants to end the program. 2

5. Compute the real solutions of the equation


f (x) = 0

(10)

of the continuous, nonlinear function f (x) numerically, using the method. This approach assumes that there exists an interval I = [ai , bi ] with f (ai ) f (bi ) < 0, whereby due to continuity, a solution u exists inside of I with f (u) = . Both initial conditions a0 and b0 should be read as user input as proper approximations of the searched solution u. The solution is computed iteratively by systematically decreasing the intervals, where the next approximation of the solution (bi ai ) ui = ai f (ai ) (11)

regula falsi

f (bi ) f (ai )

is evaluated as zero of the linear interpolating function of the base points ai and bi with values f (ai ) and f (bi ). The sign of f (ui ) determines the interval for searching the solution u. Consequently, the following rule of iteration is obtained:
calculate ui then if else ai+1 = ui , bi+1 = bi (f (ui )f (ai ) < 0) bi+1 = ui , ai+1 = ai

Test the program for the following functions and compare with exact results (a) (b) (c) (d)
f (x) = sin(x) f (x) = (x + 1) (x 1) = x2 1 f (x) = tan(x) x 1 f (x) = 3x + sin(x) exp(x).

6. Given N (t) radioactive nuclei, they will decay randomly according to the following equation: N (t) dN = . (12)
dt

This equation can be solved analytically as N (t) = N (0)exp(t/ ), where N (0) is the initial number of radioactive nuclei. This solution allows us to compare our numerical results with the exact solution.

Solve the dietential equation numerically using the 4th order RungeKutta method (RK4). Let an initial value problem be specied as follows. y = f (t, y), y(t0 ) = y0 . (13) Then, the RK4 method for this problem is given by the following equations:
yn+1 = yn + tn+1 h (k1 + 2k2 + 2k3 + k4 ) 6 = tn + h

(14) (15) (16) (17) (18) (19)

where yn+1 is the RK4 approximation of y(tn+1 ), and


k1 = f (tn , yn ) h h k2 = f tn + , yn + k1 2 2 h h k3 = f tn + , yn + k2 2 2 k4 = f (tn + h, yn + hk3 )

Numerically solve for the time dependence N (t) for the interval 0.0s t 15.0s assuming N (0) = 100% and = 2s. Do this for the following values of t : 0.1s, 0.01s, 0.001s. Compare your results to the exact solution to this equation. 7. Create a program to nd all the prime numbers between 1 and 100. One way to do this is to write a function that will check if a number is prime (i.e., see if the number can be divided by a prime number smaller than itself) using a vector of primes in order (so that if the vector, is called primes then primes[O]=2, primes[1]=3, primes[2]=5, etc.). Thereafter write a loop that goes from 1 to 100, checks each number to see if it is a prime, and stores each prime found in a vector. Write another loop that lists the primes you found on screen. Consider 2 to be the rst prime. 8. An ecient method of sorting the elements of an array is called quicksort. The method can described by the following recursive algorithm. (a) Pick an element, called a pivot, from the list. (b) Reorder the list so that all elements which are less than the pivot come before the pivot and so that all elements greater than the pivot come after it (equal values can go either way). (c) After this partitioning, the pivot is in its nal position. This is called the partition operation. 4

(d) Recursively sort the sub-list of lesser elements and the sub-list of greater elements. The base case of the recursion are lists of size zero or one, which are always sorted. Write a function template that sorts an array with elements of types char, int and double. The function should be able to sort arrays of dierent lengths. 9. Write a program that inputs a time from the console. The time should be in the format "HH:MM AM"or "HH:MM PM". Hours may be one or two digits, "1:10 AM"or "11:30 PM". Your program should include a function that takes a string parameter containing the time. This functions should convert the time into a four digit military time based on a 24-hour clock. For example, "1:10 AM"would output "0110 hours", "11:30 PM"would output "2230 hours"and "12:15 AM"would output "0015 hours". The function may either write the time to the console or return a string to be written to the console by the main program. Hint: you can use either string class or C- style character arrays and string functions to manipulate strings. 10. Design and implement a simple weather measurement register. The program has to keep a le on a hard drive. In other words the program loads previously given information from the le when it starts and writes it in the same le when it ends. The register should contain information about the place and date of the measurement (the measurement are always performed at the same time of a day), temperature, wind speed and direction, relative humidity and the amount of rain (mm/24hours). The program should be able to print for example the average temperature of a given time interval, average wind speed and the total amount of rain. Printing on screen is enough. The user interface should be as simple as possible. 11. Design a class Vector for the three-dimensional vectors with three cartesian coordinates x,y,z as members. Overload operators + (sum of vectors), (substraction of vectors) and (dot product). Dene also a member function cross for the cross product. Write a program which asks two vectors from the user and prints their sum, substraction, dot and cross products. 12. Dene a class for triangles given three by vertices, each of which is represented by an object of another class for three-dimensional points. Using member initializer lists, dene two constructors for it: one with three points as arguments for the three vertices and another 5

with two points (the third vertex is by default to be in the origin). Also dene a member function that moves a triangle to a new location and another member function that prints out the coordinates of the three vertices of a triangle. Create a few triangle objects, move them to new locations and print out the coordinates of triangles before and after moving them. 13. Implement a template class Stack, where you store some objects. Stacks are a type of container, specically designed to operate in a LIFO context (last-in rst-out), where elements are inserted and extracted only from the end of the container. Elements are pushed/popped from the "back"of the specic container, which is known as the top of the stack. Write methods push and pop to store in and retrieve the integers. In your design, use classes, dynamical memory allocation, and pointers. Write a main program where you demonstrate how your stack works for datatypes int, char and string. 14. Implement the class hierarchy for points in one, two and three dimensions as outlined in lecture notes, using pointers for their data members. User dened copy constructor and copy assignment need to be dened for them and also a virtual destructor is needed for the base class Pt. Add more functions such as moving a point and nding the equation of the line passing through two points and evaluate the distance between two points. Create a vector of (pointers to) points and and print them out using run-time polymorphism. 15. Dene a structure called Date that contains two int members month and day. Use random number generator rand() to generate a multiset of 100 Dates, representing people's birthdays. Then write a dunction to nd how many people in the multiset have a given birthday. 16. Create two arrays vector<double> called x and y of the same size. Create a routine which returns a random number and enter some random numbers into these arrays using the generate STL algorithm. These are the x and y coordinates of points on a 2D plane. Use the for_each STL algorithm to print the x coordinates and the y coordinates (separately). Write a function which takes a single double value d as a parameter, and returns 2 d. 6

Use then the transform STL algorithm to double all the numbers in the x vector. Write a suitable function and use the transform STL algorithm to compute the distance of each point (x[i], y[i]) from the origin, storing the result in a new vector called length. Use suitable STL algorithms to nd the distances of the point which is nearest and furthest from the origin. 17. Study how to link the "Numerical Recipes" library in a C++ project. Solve the eigenvalues and eigenvectors of real symmetric matrix given below
.

A=

1 2 3 4

2 3 4 5

3 4 5 6

4 5 6 7

(20)

You nd some useful les for "Numerical Recipes" in Moodle. 18. Study how to link library in a C++ project. Use GSL library and solve the eigenvalues and eigenvectors of real symmetric matrix given below

GNU GSL

2 1 0 A = 1 2 1 . 0 1 2

(21)

19. The Dung oscillator is a damped nonlinear and periodically forced pendulum described by the dierential equation
d2 x dx = ax3 + bx + c 2 dt dt + F cos(t).

(22)

Using the Euler's predictor-corrector method write a program that yields a plot of the the velocity versus the position for a Dung oscillator with parameters a = 1, b = 0, c = 0.3, F = 10 for 40000 time steps of length 0 = 0.03 and the starting values (initial conditions) x0 = 1 and v0 = 6. See also what happens when you change these values. Hint: for solving the initial value problem y (x) = f (x, y), y(x0 ) = y0 . (23)

Euler's predictor-corrector method


7

is given by equations
xn+1 = xn + h k1 = yn + h f (xk , yk ) yn+1 = yn + h f (xk+1 , k1).

(24) (25) (26)

For drawing the plot you can use the FLTK graphics library as described in lecture notes. 20. Laplace's equation ( ): in two dimensions the problem is to nd twice-dierentiable real-valued functions u(x, y) such that
2

dicult!

u(x, y) =

2u 2u + 2 = 0. x2 y

(27)

Solutions of Laplace's equation are called harmonic functions. If the right-hand side is specied as a given function, g(x, y, z), i.e.
2

u(x, y) = g(x, y)

(28)

then the equation is called Poisson's equation. The Dirichlet problem for Laplace's equation consists of nding a solution on some domain such that on the boundary of is equal to some given function. Since the Laplace operator appears in the heat equation, one physical interpretation of this problem is as follows: x the temperature on the boundary of the domain and wait until the temperature in the interior doesn't change anymore; the temperature distribution in the interior will then be given by the solution to the corresponding Dirichlet problem. In this project we seek solutions of the Dirichlet's problem
2

u(x, y) =

2u 2u + 2 = 0, x2 y

0 < x < N, 0 < y < M

(29)

with the boundary conditions


u(x, 0) = 20 ; u(x, M ) = 180 (0 < x < N ); u(0, y) = 80 ; u(N, y) = 0 (0 < y < M );

(30) (31)

Let N = 4 amd M = 4, then The problem is to solve the Laplace's equation on the square domain = (x; y) : 0 < x < N, 0 < y < M on the points (xi , xj ), where i = 1, . . . , n and j = 1, . . . , m when n and m are discrete grids in the x- and y- axes, respectively.

You might also like