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

Create the noisy data

In [3]:
sigma = 5
x = np.linspace(-20,20)
y = gaussian(x, sigma) + 0.01*noise(x)

plt.scatter(x, y)

<matplotlib.collections.PathCollection at 0x7f9d4c8e2048>

Fit the data

In [4]:
popt, pcov = optimize.curve_fit(gaussian, x, y)

plt.scatter(x, y, label="data")
plt.plot(x, gaussian(x, *popt), label="fit")

print("best fit for sigma: " + str(popt[0]))
print("actual value for sigma: " + str(sigma))

best fit for sigma: 4.73706945436
actual value for sigma: 5