import numpy as np
import matplotlib.pyplot as plt

# Data, hard-wired into the code
x = np.array([1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00])
y = np.array([4.09, 4.34, 4.88, 5.52, 5.91, 5.93, 6.67, 6.96, 7.41, 7.94])
slope_true = 0.45
intercept_true = 3.38

# Various sums needed
sum_x = np.sum(x)
sum_xx = np.sum(x**2)
sum_y = np.sum(y)
sum_xy = np.sum(x*y)
n = float(len(x))

# Use formula
slope = (n*sum_xy - sum_x*sum_y) / (n*sum_xx - sum_x**2)
intercept = (sum_y*sum_xx - sum_xy*sum_x) / (n*sum_xx - sum_x**2)

# Matrix
mat = np.matrix([[sum_xx, sum_x],
								 [sum_x, n]])
vec = np.matrix([[sum_xy],
							   [sum_y]])
ans = mat.I * vec
slope = ans.A[0][0]
intercept = ans.A[1][0]

# Plot the fit results
plt.plot(x, y, 'ob')
plt.plot(x, slope*x + intercept, '-r')
plt.plot(x, slope_true*x + intercept_true, '-g')
plt.show()
