Skip to content

Instantly share code, notes, and snippets.

@aijony
Created November 12, 2017 16:22
Show Gist options
  • Save aijony/d2603e856248b92ebe4e722ab2c156a0 to your computer and use it in GitHub Desktop.
Save aijony/d2603e856248b92ebe4e722ab2c156a0 to your computer and use it in GitHub Desktop.
Minumum Least Squares Through Trial and Error
data = [(0, 0), (1, 2), (2, 4), (3, 6), (4, 8)]
m = 0
b = 0
def testFunc(x):
return m * x + b
def leastSquares(func, data):
results = 0
for datum in data:
x = datum[0]
y = datum[1]
results = results + (y - func(x))**2
return results
def adjustFunc():
global data, m, b
best = leastSquares(testFunc, data)
mod = 1
while(True):
m = m + mod
curr = leastSquares(testFunc, data)
if(best > curr):
best = curr
elif(best < curr):
m = m - mod
mod = -(1/10) * mod
else:
return m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment