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)
def line(x, a, b):
return a * x + b
def parabola(x, a, b, c):
return a * x ** 2 + b * x + c
from scipy.optimize import curve_fit
popt1, pcov1 = curve_fit(line, x, y, sigma=e)
popt2, pcov2 = curve_fit(parabola, x, y, sigma=e)
%matplotlib inline
import matplotlib.pyplot as plt
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)
import numpy as np
date, temperature = np.loadtxt('data/munich_temperatures_average_with_bad_data.txt', unpack=True)
keep = np.abs(temperature) < 90
date = date[keep]
temperature = temperature[keep]
def cosine(x, a, b, c):
return a * np.cos(2 * np.pi * x + b) + c
popt, pcov = curve_fit(cosine, date, temperature)
plt.plot(date, temperature, '.')
xfine = np.linspace(1995, 2014, 100)
plt.plot(xfine, cosine(xfine, *popt), color='red', lw=2)
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:
from scipy.integrate import quad
quad(gaussian, -100., 100., args=(1., 0., 1.))
The integral is 1, as expected. We can now try and do the same with discrete samples:
from scipy.integrate import simps
x = np.linspace(-100., 100., 10000)
y = gaussian(x, 1., 0., 1.)
simps(y, x=x)