The first python exercise involves some simple tasks in order to get familiar with Python.
Perform the following simple tasks.
a) Write a Python program that writes "Hello, World!" to the screen.
print 'Hello, World!'
b) In this subexercise some simple mathematical operations are to be carried out. Define the vectors \( a \) and \( b \) and the matrices \( A \) and \( B \) as numpy arrays as follows, $$ \begin{align*} a&=\left[ \begin{matrix} 1 \\ 2 \\ 3 \end{matrix}\right] & b&=\left[ \begin{matrix} 4 \\ 5 \\ 6 \end{matrix}\right] & A&=\left[ \begin{matrix} 1 & 1 & 2 \\ 2 & 3 & 3 \\ 4 & 4 & 5 \end{matrix}\right] & B&=\left[ \begin{matrix} 2 & 4 & 6 \\ 8 & 10 & 12 \\ 14 & 16 & 18 \end{matrix}\right] \end{align*} $$ Carry out the following calculations and print the results to the screen:
For the latter two calculations some functions in numpy.linalg might be useful. See http://docs.scipy.org/doc/numpy/reference/routines.linalg.html.
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
A = np.array([[1,1,2],[2,3,3],[4,4,5]])
B = np.array([[2,4,6],[8,10,12],[14,16,18]])
print a+b
print np.dot(a,b)
print np.dot(A,B)
print np.transpose(A)
print np.linalg.inv(A)
print np.linalg.solve(A,b)
c)
Implement a function fib(n) that writes the first n elements in the Fibonacci series to the screen. Write the first 20 elements to the screen.
def fib(n):
"""Write the Fibonacci series up to and including element n."""
a, b, i = 0, 1, 1
while i <= n:
print a,
a, b, i = b, a+b, i+1
fib(20)
d) Plot \( sin(x) \) from \( x=0 \) to \( x=2\pi \) with 10 and 100 points. Make the figure presentable by naming the axes, set different colors to the lines, including legend etc. Save the figure as a file.

import matplotlib.pylab as plt
import numpy as np
x1 = np.linspace(0,2*np.pi,10)
x2 = np.linspace(0,2*np.pi,100)
u1 = np.sin(x1)
u2 = np.sin(x2)
plt.figure()
plt.rcParams['font.size'] = 16
plt.plot(x2,u2,'g.-',x1,u1,'r-v',markersize=10,linewidth=2)
plt.legend(['100 points','10 points'], loc='best', frameon=False)
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Plot of sin(x)')
plt.grid()
plt.savefig("sinus_plot.png", transparent=True)
plt.show()
e)
Rewrite the function fib(n) such that the sum of the series is stored in a variable (numpy array). Plot the first 30 first values in the variable with logarithmic y-axis. Make the plot presentable.

import matplotlib.pylab as plt
def fib_sum(n):
"""Plots the sum of the elements in the Fibonacci series up to and including element n."""
a, b, i = 0, 1, 0
fibsum = []
while i < n:
fibsum.append(a)
a, b, i = b, a+b, i+1
return fibsum
fibsum = fib_sum(30)
plt.plot(fibsum, color='r', marker='o', linewidth=2, markersize=8, markerfacecolor='g', markeredgecolor='b')
plt.rcParams['font.size'] = 16
plt.ylabel('Sum of the Fibonacci series')
plt.title('Fibonacci')
plt.yscale('log')
plt.grid()
plt.savefig('fibonacci_plot.png', transparent=True)
plt.show()