.. !split .. _basics:exer: Exercises ========= .. --- begin exercise --- .. _basics:exer:formula1: Exercise 1: Program a formula ----------------------------- **a)** Make a simplest possible Python program that calculates and prints the value of the formula .. math:: y = 6x^2 + 3x + 2, for $x=2$. .. --- begin solution of exercise --- **Solution.** The complete program reads .. code-block:: python x = 2 y = 6*x**2 + 3*x + 2 print y .. --- end solution of exercise --- **b)** Make a Python function that takes :math:x as argument and returns :math:y. Call the function for :math:x=2 and print the answer. .. --- begin solution of exercise --- **Solution.** Code: .. code-block:: python def f(x): return 6*x**2 + 3*x + 2 y = f(2) print y .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:printf1: Exercise 2: Combine text and numbers in output ---------------------------------------------- Let :math:y=x^2. Make a program that writes the text .. code-block:: text y(2.550)=6.502 if :math:x=2.55. The values of :math:x and :math:y should be written with three decimals. Run the program for :math:x=\pi too (the value if :math:\pi is available as the variable pi in the math module). .. --- begin solution of exercise --- **Solution.** Here is the code: .. code-block:: python x = 2.55 y = x**2 print 'y(%.3f)=%.3f' % (x, y) Changing :math:x=2.55 to :math:x=\pi, .. code-block:: python from math import pi x = pi y = x**2 print 'y(%.3f)=%.3f' % (x, y) gives the output y(3.142)=9.870. .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:while1: Exercise 3: Program a while loop -------------------------------- Define a sequence of numbers, .. math:: x_n = n^2 + 1, for integers :math:n=0,1,2,\ldots,N. Write a program that prints out :math:x_n for :math:n=0,1,\ldots,20 using a while loop. .. --- begin solution of exercise --- **Solution.** Complete program: .. code-block:: python n = 0 while n <= 20: x_n = n**2 + 1 print 'x%d=%d' % (n, x_n) n = n + 1 .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:while2: Exercise 4: Create a list with a while loop ------------------------------------------- Store all the :math:x_n values computed in :ref:basics:exer:while1 in a list (using a while loop). Print the entire list (as one object). .. --- begin solution of exercise --- **Solution.** Code: .. code-block:: python n = 0 x = [] # the x_n values while n <= 20: x.append(n**2 + 1) n = n + 1 print x .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:for1: Exercise 5: Program a for loop ------------------------------ Do :ref:basics:exer:while2, but use a for loop. .. --- begin solution of exercise --- **Solution.** Code: .. code-block:: python x = [] for n in range(21): x.append(n**2 + 1) print x One can also make the code shorter using a list comprehension: .. code-block:: python x = [n**2 + 1 for n in range(21)] print x .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:func1: Exercise 6: Write a Python function ----------------------------------- Write a function x(n) for computing an element in the sequence :math:x_n=n^2+1. Call the function for :math:n=4 and write out the result. .. --- begin solution of exercise --- **Solution.** Code: .. code-block:: python def x(n): return n^2 + 1 print x(4) .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:func3: Exercise 7: Return three values from a Python function ------------------------------------------------------ Write a Python function that evaluates the mathematical functions :math:f(x)=\cos(2x), :math:f'(x)=-2\sin(2x), and :math:f''(x)=-4\cos(2x). Return these three values. Write out the results of these values for :math:x=\pi. .. --- begin solution of exercise --- **Solution.** Code: .. code-block:: python from math import sin, cos, pi def deriv2(x): return cos(2*x), -2*sin(2*x), -4*cos(2*x) f, df, d2f = deriv2(x=pi) print f, df, d2f Running the program gives .. code-block:: text Terminal> python deriv2.py 1.0 4.89858719659e-16 -4.0 as expected. .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:plot1: Exercise 8: Plot a function --------------------------- Make a program that plots the function :math:g(y)=e^{-y}\sin (4y) for :math:y\in [0,4] using a red solid line. Use 500 intervals for evaluating points in :math:[0,4]. Store all coordinates and values in arrays. Set labels on the axis and use a title "Damped sine wave". .. --- begin solution of exercise --- **Solution.** Appropriate code is .. code-block:: python import numpy as np import matplotlib.pyplot as plt from numpy import exp, sin # avoid np. prefix in g(y) formula def g(y): return exp(-y)*sin(4*y) y = np.linspace(0, 4, 501) values = g(y) plt.figure() plt.plot(y, values, 'r-') plt.xlabel('$y$'); plt.ylabel('$g(y)$') plt.title('Damped sine wave') plt.savefig('tmp.png'); plt.savefig('tmp.pdf') plt.show() .. figure:: plot_exer1.png :width: 500 .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:plot2: Exercise 9: Plot two functions ------------------------------ As :ref:basics:exer:plot2, but add a black dashed curve for the function :math:h(y)=e^{-\frac{3}{2}y}\sin (4y). Include a legend for each curve (with names g and h). .. --- begin solution of exercise --- **Solution.** Here is the program: .. code-block:: python import numpy as np import matplotlib.pyplot as plt from numpy import exp, sin # avoid np. prefix in g(y) and h(y) def g(y): return exp(-y)*sin(4*y) def h(y): return exp(-(3./2)*y)*sin(4*y) y = np.linspace(0, 4, 501) plt.figure() plt.plot(y, g(y), 'r-', y, h(y), 'k--') plt.xlabel('$y$'); plt.ylabel('$g(y)$') plt.title('Damped sine wave') plt.legend(['g', 'h']) plt.savefig('tmp.png'); plt.savefig('tmp.pdf') plt.show() .. figure:: plot_exer2.png :width: 500 .. --- end solution of exercise --- .. --- end exercise --- .. --- begin exercise --- .. _basics:exer:timeit: Exercise 10: Measure the efficiency of vectorization ---------------------------------------------------- IPython __ an enhanced interactive shell for doing computing with Python. IPython has some user-friendly functionality for quick testing of the efficiency of different Python constructions. Start IPython by writing ipython in a terminal window. The interactive session below demonstrates how we can use the timer feature %timeit to measure the CPU time required by computing :math:\sin (x), where :math:x is an array of 1M elements, using scalar computing with a loop (function sin_func) and vectorized computing using the sin function from numpy. .. code-block:: ipy In [1]: import numpy as np In [2]: n = 1000000 In [3]: x = np.linspace(0, 1, n+1) In [4]: def sin_func(x): ...: r = np.zeros_like(x) # result ...: for i in range(len(x)): ...: r[i] = np.sin(x[i]) ...: return r ...: In [5]: %timeit y = sin_func(x) 1 loops, best of 3: 2.68 s per loop In [6]: %timeit y = np.sin(x) 10 loops, best of 3: 40.1 ms per loop Here, %timeit ran our function once, but the vectorized function 10 times. The most relevant CPU times measured are listed, and we realize that the vectorized code is :math:2.68/(40.1/1000)\approx 67 times faster than the loop-based scalar code. Use the recipe above to investigate the speed up of the vectorized computation of the :math:s(t) function in the section :ref:basics:func. .. factor 134 .. --- end exercise ---