In [1]:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from scipy import optimize
In [2]:
def gaussian(x, sigma):
y = (2*np.pi*sigma**2)**-.5 * np.exp(-.5*(x/sigma)**2.)
return y
def noise(x):
y_noise = np.random.normal(size=len(x))
return y_noise
In [3]:
sigma = 5
x = np.linspace(-20,20)
y = gaussian(x, sigma) + 0.01*noise(x)
plt.scatter(x, y)
Out[3]:
In [4]:
popt, pcov = optimize.curve_fit(gaussian, x, y)
plt.scatter(x, y, label="data")
plt.plot(x, gaussian(x, *popt), label="fit")
plt.legend(loc="best")
print("best fit for sigma: " + str(popt[0]))
print("actual value for sigma: " + str(sigma))