## Exercise 1¶

In [1]:
import numpy as np
x = np.random.uniform(0., 10., 100)
y = np.polyval([1, 2, -3], x) + np.random.normal(0., 10., 100)
e = np.random.uniform(5, 10, 100)

In [2]:
def line(x, a, b):
return a * x + b

In [3]:
def parabola(x, a, b, c):
return a * x ** 2 + b * x + c

In [4]:
from scipy.optimize import curve_fit
popt1, pcov1 = curve_fit(line, x, y, sigma=e)
popt2, pcov2 = curve_fit(parabola, x, y, sigma=e)

In [5]:
%matplotlib inline
import matplotlib.pyplot as plt

In [6]:
plt.errorbar(x, y, yerr=e, fmt="none")
xfine = np.linspace(0., 10., 100)
plt.plot(xfine, line(xfine, *popt1), color='red', lw=2)
plt.plot(xfine, parabola(xfine, *popt2), color='orange', lw=2)

Out[6]:
[<matplotlib.lines.Line2D at 0x10ed2d780>]

### Exercise 2¶

In [7]:
import numpy as np
keep = np.abs(temperature) < 90
date = date[keep]
temperature = temperature[keep]

In [8]:
def cosine(x, a, b, c):
return a * np.cos(2 * np.pi * x + b) + c

In [9]:
popt, pcov = curve_fit(cosine, date, temperature)

In [10]:
plt.plot(date, temperature, '.')
xfine = np.linspace(1995, 2014, 100)
plt.plot(xfine, cosine(xfine, *popt), color='red', lw=2)

Out[10]:
[<matplotlib.lines.Line2D at 0x105c78198>]

## 16. Interpolation and Integration¶

In [11]:
def gaussian(x, amplitude, mean, sigma):
return 1. / (np.sqrt(2 * np.pi) * sigma) * np.exp(-0.5 * (x - mean)**2 / sigma**2)


Here we can't simply call quad with gaussian and the limits - we also have to specify the additional parameters (amplitude, mean, and sigma). We can use the args option for this:

In [12]:
from scipy.integrate import quad
quad(gaussian, -100., 100., args=(1., 0., 1.))

Out[12]:
(1.0000000000000002, 1.0346447325665705e-12)

The integral is 1, as expected. We can now try and do the same with discrete samples:

In [13]:
from scipy.integrate import simps
x = np.linspace(-100., 100., 10000)
y = gaussian(x, 1., 0., 1.)
simps(y, x=x)

Out[13]:
1.0